- 數(shù)組雜記
1)數(shù)組的判斷西篓,使用Array.isArray()
var number = 1;
var arrays = [1, 2, 'number', null];
Array.isArray(number) // false
Array.isArray(arrays) // true
2)一維數(shù)組的深拷貝
// for循環(huán)
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); // 為數(shù)組做個副本
// concat
var arr1 = [1, 2, 3, 4];
var arr2 = arr1.concat();
// 擴展運算符...
var arr1 = [1, 2, 3, 4];
var [ ...arr2 ] = arr1;
3)多維數(shù)組的深拷貝
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)數(shù)組去重
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;