一. 数组判断
- 情况一
js
const target = {}
function isArray(target) {
return Object.prototype.toString.call(target) === "[object Array]"
}
console.log(isArray(target)) // false
js
const target = {
[Symbol.toStringTag]: "Array",
}
function isArray(target) {
return Object.prototype.toString.call(target) === "[object Array]"
}
console.log(isArray(target)) // true
- 情况二
js
const target = {}
function isArray(target) {
return target instanceof Array
}
console.log(isArray(target)) // false
js
const target = {}
Object.setPrototypeOf(target, Array.prototype)
function isArray(target) {
return target instanceof Array
}
console.log(isArray(target)) // true
使用ES6
js
const target = {
[Symbol.toStringTag]: "Array",
}
Object.setPrototypeOf(target, Array.prototype)
function isArray(target) {
return Array.isArray(target)
}
console.log(isArray(target)) // false
二. 原始值转换
- 情况一
js
const target = {}
console.log(target.toString()) // [object Object]
console.log(target + 1) // [object Object]1
- 情况二
js
const target = {
toString() { return 1 },
}
console.log(target.toString()) // 1
console.log(target + 1) // 2
- 情况三
js
const target = {
toString() { return 1 },
valueOf() {
return 2
},
}
console.log(target.toString()) // 1
console.log(target + 1) // 3
- 情况四 参考mdn
js
const target = {
toString() { return 1 },
valueOf() {
return 2
},
[Symbol.toPrimitive](hint) {
return 3
},
}
console.log(target.toString()) // 1
console.log(target + 1) // 4
原始值强制转换优先权重:[Symbol.toPrimitive]
> valueOf
> toString