You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断值是普通数组而非数组原型?

区分普通数组与数组原型的方法

要检测一个值是普通数组但排除Array.prototype,可以在Array.isArray的基础上,额外判断该值是否严格等于Array.prototype:

function isPlainArray(value) {
  return Array.isArray(value) && value !== Array.prototype;
}

测试验证:

isPlainArray([]); // true
isPlainArray(Object.getPrototypeOf([])); // false(Object.getPrototypeOf([])即为Array.prototype)
isPlainArray(new Array()); // true
isPlainArray(Array.prototype); // false

原理很直接:Array.prototype本身确实会被Array.isArray判定为数组,但它是所有原生数组的原型对象,我们只需要把这个特殊对象从检测结果里排除即可。

如果需要兼容一些特殊场景(比如自定义继承数组的对象),也可以结合构造函数判断:

function isPlainArray(value) {
  return value?.constructor === Array && value !== Array.prototype;
}

这个方法同样能区分普通数组和数组原型,不过如果是修改过constructor的自定义数组对象,结果可能不符合预期,若你的场景只针对原生数组,第一种方法更可靠。

内容的提问来源于stack exchange,提问作者Ood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 23:12:02