我很好奇是否有任何方法可以用用户定义的对象伪造出 Array.isArray()
。
摘自《JavaScript 模式》一书:
Array.isArray([]); // true
// trying to fool the check
// with an array-like object
Array.isArray({
length: 1,
"0": 1,
slice: function () {}
}); // false
那个对象显然失败了,但是还有其他方法吗?这纯粹是出于好奇,并不是因为我认为您可以在常规客户端代码中搞砸 .isArray()
(尽管知道如果可以的话显然会很棒!)。
最佳答案
仅当您设置 internal [[Class]]
property到 "Array"
,这是不可能的 afaik。来自specification :
The
isArray
function takes one argumentarg
, and returns the Boolean valuetrue
if the argument is an object whose class internal property is "Array"; otherwise it returnsfalse
.
或者你反过来:创建一个普通数组并将每个数组方法显式设置为 undefined
。
关于javascript - 你能用用户定义的对象伪造 Array.isArray() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8672038/