2016-08-12 5 views
1

var strに値を代入すると、文字列をバイトに変換したいのですが、$scope.event[]を割り当てると、エラーstr.charCodeAt is not a functionが発生します。$scope.event[0]は、最初のインデックスのバイトだけを返します。配列の総バイト数を取得するにはどうすればよいですか?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 script) – jonhopkins

答えて

0

あなたはmap/reduce配列コードをcharに文字列を変換することができます。あなたのキーワードにmapを実行することから始まります(各配列を別の配列に変換したい)、各単語を配列に分割して、各文字を処理してその文字配列をcharCodeの合計に減らします。

$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

私が提供したコードは、配列内の各文字列のcharCodeの合計を計算する役割しか果たしません。あなたの全体的な目標が何であるか、そしてあなたの関数が何をしているのかは正確には分かりません。繰り返します:文字列の配列( '$ scope.event')は整数の配列に変換されます。 –

関連する問題