我想将字符串转换为字节,它工作得很好,如果我将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();
[循环通过阵列$ scope.event ...](http://stackoverflow.com/questions/1128388/looping-through-elements-of-an- array-in-java脚本) – jonhopkins