2016-08-12 59 views
1

我想将字符串转换为字节,它工作得很好,如果我将var str设置为$scope.event[0],那么它只给第一个索引提供字节,如果我分配$scope.event[],它将会抛出错误str.charCodeAt is not a function。我怎样才能获得数组的总字节数?如何使用charCode赋值?

ctrl.js

$scope.event = ["lorem ipsum", "lorem ipsum","lorem ipsum"] 

    function jsonToArray() { 
      var total = 0; 
      var str = $scope.event; 
      var bytes = []; // char codes 
      var bytesv2 = []; // char codes 

      for (var i = 0; i < str.length; ++i) { 
       var code = str.charCodeAt(i); 
       bytes = bytes.concat([code]); 
       bytesv2 = bytesv2.concat([code & 0xff, code/256 >>> 0]); 
      } 
      var totalBytes = 0; 
      console.log('bytes', bytes.join(', ')); 
      for (var i = 0 ; i < bytes.length ; i++) { 
       totalBytes += bytes[i]; 
       totalCurrentBytes.push(totalBytes); 
      } 
      console.log('Total bytes', totalBytes); 
      formatBytes(totalBytes); 
     } 

    jsonToArray(); 
+0

[循环通过阵列$ scope.event ...](http://stackoverflow.com/questions/1128388/looping-through-elements-of-an- array-in-java脚本) – jonhopkins

回答

0

可以map/reduce数组到字符串转换为char代码。通过在您的关键字上运行map(我们希望将一个数组转换为另一个数组),将每个单词分割成一个数组,以便您处理每个字母,并将该字符数组减少为它们的总和charCode s:

$scope.event.map(word => word.split('').reduce((total,cur) => total + cur.charCodeAt(0), 0)); 

非ES6

$scope.event.map(function(word) { 
    return word.split(' ').reduce(function(total, cur) { 
     return total + cur.charCodeAt(0); 
    }, 0); 
}); 
+0

感谢您的回答,所以我的其他代码将保持不变? – hussain

+0

我提供的代码仅用于计算数组中每个字符串的charCodes总和,我不确定您的总体目标是什么以及您的函数还有什么功能。重申:一个字符串数组($ scope.event)将被转换成一个整数和的数组。 –