- 数组杂记
1)数组的判断,使用Array.isArray()
var number = 1;
var arrays = [1, 2, 'number', null];
Array.isArray(number) // false
Array.isArray(arrays) // true
2)一维数组的深拷贝
// for循环
function copy(arr1, arr2) {
for (var i = 0; i < arr1.length; i++) {
arr2[i] = arr1[i]
}
}
// slice
var arr1 = [1, 2, 3, 4];
var arr2 = arr1.slice(0); // 为数组做个副本
// concat
var arr1 = [1, 2, 3, 4];
var arr2 = arr1.concat();
// 扩展运算符...
var arr1 = [1, 2, 3, 4];
var [ ...arr2 ] = arr1;
3)多维数组的深拷贝
function deepCopy(array) {
var copy = []
for (var i = 0; i < array.length; i++) {
if (array[i] instanceof Array) {
copy[i] = deepCopy(array[i])
} else {
copy = array[i]
}
}
return copy;
}
4)数组去重
function distinct(array) {
return [...new Set(array)]
}
var arr = [1, 1, 2, 3, 4, 4, 4];
distinct(arr) // [1, 2, 3, 4]
- 对象杂记
1)对象的深拷贝
// 扩展运算符...
var obj1 = {
name: 'Tom',
age: 10,
gender: '男'
}
var { ...obj2 } = obj1;