【问题标题】:how to assign value using charCode?如何使用 charCode 赋值?
【发布时间】:2016-12-19 18:01:54
【问题描述】:

我想将字符串转换为字节,如果我将值分配给var str$scope.event[0],它工作正常,它只给我第一个索引的字节,如果我分配$scope.event[] 它会抛出错误str.charCodeAt is not a function。我怎样才能得到数组的总字节数?

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();

【问题讨论】:

标签: javascript arrays binary


【解决方案1】:

您可以通过map/reduce 数组将字符串转换为字符代码。首先在您的关键字上运行map(我们希望将一个数组转换为另一个),对于每个单词,将单词拆分为一个数组,以便您处理每个字母并将该字符数组减少为它们的总和@987654326 @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);
});

【讨论】:

  • 感谢您的回答,所以我的其他代码将保持不变?
  • 我提供的代码仅用于计算数组中每个字符串的 charCodes 的总和,我不确定您的总体目标是什么以及您的函数还有什么作用。重申一下:字符串数组 ($scope.event) 将转换为整数和数组。
猜你喜欢
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 2015-01-11
  • 1970-01-01
相关资源
最近更新 更多