如果a是Array的一个实例。我们知道typeof a会返回'object',但是我想让它返回'array',我能这样做吗?
如果我可以,那我怎么做呢?如果不行,那为什么不呢?
发布于 2019-04-01 00:41:09
不,你不能-数组是一个对象,简单明了:
const aRealArray = [1, 2, 3];
console.log(typeof aRealArray);
但是,您可以通过使用Array.isArray或instanceof来检查某物是否是数组。
const aRealArray = [1, 2, 3];
console.log(Array.isArray(aRealArray));
console.log(aRealArray instanceof Array);
console.log(Object.prototype.toString.call(aRealArray));
请注意,Array.isArray是更可靠的版本(正如@MattBrowne在下面的comments中指出的那样,它跨iframes工作)。instanceof只需检查Array.prototype是否在原型链上。
发布于 2019-04-01 00:44:50
尝试使用数组的"isArray“方法,该方法返回一个布尔值:
Array.isArray(a)https://stackoverflow.com/questions/55446771
复制相似问题