我必须使用Javascript验证提供的参数是否是一种字节数组。我怎样才能做到这一点?请指教。
答案 0 :(得分:2)
由于不清楚您要检查的Typed-Array的类型/实例,这里是一个通用检查。检查 byteLength 是否存在,那么它应该是字节数组
function isByteArray(array) {
if (array && array.byteLength !== undefined) return true;
return false;
}
function toUTF8Array(str){ var utf8 = new ArrayBuffer(str.length);
for (var i=0; i < str.length; i++) {
var charcode = str.charCodeAt(i);
if (charcode < 0x80) {
utf8[i] = charcode;
continue;
}
if (charcode < 0x800) {
utf8[i] = (0xc0 | (charcode >> 6),
0x80 | (charcode & 0x3f));
continue;
}
if (charcode < 0xd800 || charcode >= 0xe000) {
utf8[i] = (0xe0 | (charcode >> 12),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
continue;
}
i++;
charcode = 0x10000 + (((charcode & 0x3ff)<<10)
| (str.charCodeAt(i) & 0x3ff));
utf8[i - 1] = (0xf0 | (charcode >>18),
0x80 | ((charcode>>12) & 0x3f),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
return utf8;
}