[Javascript] Is Array? Symbol.toStringTag

Zhentiw發表於2024-11-24

During the past, this was a working solution

function isArray(obj) {
   return Object.prototype.toString.call(obj) === '[object Array]'
}

But now it doesn't work anymore, the reason is because ES6 has a built-in Symbol:

const obj = {
   [Symbol.toStringTag]: 'Array'
}
console.log(Object.prototype.toString.call(obj)) // [object Array]

There is a second way, people might do is using instanceof Array, which also has its own problem:

function isArray(obj) {
    return obj instanceof Array;
}

const obj = {}
Object.setPrototypeof(obj, Array.prototype)

isArray(obj) // true

Also when the page has iframe, the Arrayfrom iframe is different from the Array from window.

const Array1 = window.Array
const frame = document.querySelector('iframe')
const Array2 = frame.contentWindow.Array;
console.log(Array1 === Array2) // false
isArray(Array2) // false, due to the contructor function is different, then the prototype is also different

Best way:

Array.isArray(obj) // it's code in C++

相關文章