判断Array
- typeof 返回object
console.log(typeof []) // "object"
typeof 1; // "number"
typeof null; "object"
typeof undefined; "undefined"
typeof function; "function"
- instanceof
arr instanceof Array; // true
- constructor
arr.constructor === Array; // true
2和3方法都是对原型链进行检测,但如果是跨iframe实例化的对象彼此是不共享原型链的,会导致上述方法失效
- Object.prototype.toString
Object.prototype.toString.call([]) === '[object Array]'; // true
Object.prototype.toString.call({}) === '[object Object]'; // true
- Array.isArray();
ES5方法,ie8之前不支持
判断Object
判断数组的2,3,4方法同样适用
其他数据类型判断
typeof 判断即可
Object.is 与 === 区别是
// 使用 ‘===’
+0 === -0 //true
NaN === NaN // false
// 使用 Object.is()
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true
深浅拷贝函数
- 递归实现
function deepClone(source) {
let target;
if (typeof source === 'object') {
target = Array.isArray(source) ? [] : {}
for (let key in source) {
if (source.hasOwnProperty(key)) {
if (typeof source[key] !== 'object') {
target[key] = source[key]
} else {
target[key] = deepClone(source[key])
}
}
}
} else {
target = source
}
return target
}
- JSON序列化实现
- Object.assign({}, object); 如果object字段值是简单类型就是深拷贝,如果值是引用类型就是浅拷贝
- 数组拷贝 [...arr]
网友评论