Uint16Array不是String.fromCharCode.apply的有效参数

Uint16Array not a valid argument for String.fromCharCode.apply

本文关键字:有效 参数 apply fromCharCode 不是 String Uint16Array      更新时间:2023-09-26

我在数组缓冲区和字符串之间转换的单元测试中遇到了一个奇怪的问题。

这段代码取自:http://updates.html5rocks.com/2012/06/How-to-convert-ArrayBuffer-to-and-from-String。适用于此小提琴:http://jsfiddle.net/W3DH9/

function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function str2ab(str) {
    var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
    var bufView = new Uint16Array(buf);
    for (var i=0, strLen=str.length; i<strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}
alert(ab2str(str2ab('foo')));

我实现了代码,并用jasmine为它编写了一个单元测试。这里我得到一个奇怪的错误,说TypeError: '[object Uint16Array]' is not a valid argument for 'Function.prototype.apply' (evaluating 'new Uint16Array(buf)')

我正在运行PhantomJS 1.9.7和Node v0.10.22

如果我把它记录到控制台,它是Object{prototype: Object{subarray: function subarray() { ... }, BYTES_PER_ELEMENT: 2, set: function set() { ... }}, BYTES_PER_ELEMENT: 2}

我的Chrome浏览器在本地代码中实现了这个函数。

似乎String.fromCharCode不能应用于数组类对象

这是由于PhantomJS中的一个错误:

见https://github.com/ariya/phantomjs/issues/11172