多维数组转一维数组
function flag(array) {
let length = array.length;
if (length === 0) return array;
let ret = [];
for (let item of array) {
if (item.constructor === Array) {
ret = ret.concat(flag(item));
} else {
ret.push(item);
}
}
return ret;
}
var mulitArray = [[1, [45, 23, 44], 1], 4, 25];
flag(mulitArray);
// [ 1, 45, 23, 44, 1, 4, 25 ]
两个数组的交集
function intersection(array1 = [], array2 = []) {
return array1.filter(item => array2.includes(item));
}
var array1 = [1, 2, 3, 4, 5];
var array2 = [4, 5, 6, 53];
intersection(array1, array2);
// [ 4, 5 ]
深拷贝
function deepCopy(target) {
if (typeof target !== "object") return target;
let ret;
if (Array.isArray(target)) {
ret = target.map(item => deepCopy(item));
} else {
ret = {};
Object.keys(target).forEach(item => {
ret[item] = deepCopy(target[item]);
});
}
return ret;
}
var data = [1, 2, 3, { name: "xiaoming" }];
// var data = { name: "小红", age: [23, 4] };
// var data = [1, 2, 3, [4, 1, 5]];
var result = deepCopy(data);