gpt4 book ai didi

javascript - 如何找到 typedArray 的类型?

转载 作者:行者123 更新时间:2023-11-30 10:59:52 25 4
gpt4 key购买 nike

要测试一个对象是否是一个数组,有一个方法——

const myarray = [1,2,3,4]; 
Array.isArray(myarray);
//returns true

对于类型化数组(例如,Uint8Array)是否有类似的方法?

const int8 = new Uint8Array([0,1,2,3]);
Array.isArray(int8); //returns false

如何确定一个对象是否是类型化数组,以及类型化数组的类型?

最佳答案

您可以对其构造函数1进行比较:

const int8 = new Uint8Array([0,1,2,3]);
console.log(int8.constructor === Uint8Array);

// so you can do
function checkTypedArrayType(someTypedArray) {
const typedArrayTypes = [
Int8Array,
Uint8Array,
Uint8ClampedArray,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array,
BigInt64Array,
BigUint64Array
];
const checked = typedArrayTypes.filter(ta => someTypedArray.constructor === ta);
return checked.length && checked[0].name || null;
}

console.log(checkTypedArrayType(int8));

// but this can be hugely simplified
function checkTypedArrayType2(someTypedArray) {
return someTypedArray &&
someTypedArray.constructor &&
someTypedArray.constructor.name ||
null;
}

console.log(checkTypedArrayType2(int8));

// which can actually be generalized to
const whatsMyType = someObject =>
someObject &&
someObject.constructor &&
someObject.constructor.name &&
someObject.constructor.name ||
null;

console.log(whatsMyType(int8));
console.log(whatsMyType([1,2,3,4]));
console.log(whatsMyType("hello!"))
console.log(whatsMyType(/[a-z]/i))

1 请注意,没有任何版本的 Internet Explorer 支持 name 属性。 See MDN . See also

关于javascript - 如何找到 typedArray 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58280379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com