拍平数组:
Array.prototype.concat.apply([], [1, [2,3], [4]]) //[1,2,3,4]
深度拍平:
function flattenDeep(arrs) {
let result = Array.prototype.concat.apply([], arrs);
while (result.some(item => item instanceof Array)) {
result = Array.prototype.concat.apply([], result);
}
return result;
}
console.log(flattenDeep([1,2,[5,[22,11],7,90]])); //[1,2,5,22,11,7,90]
交换变量:
[a,b] = [b,a]
some和every
有等于3的吗?true
console.log( arr.some( function( item, index, array ){
return item == 3;
}));
所有都等于3吗?false
console.log( arr.every( function( item, index, array ){
return item == 3;
}));
length
传统Length它并不是用于统计数组中元素的数量,而是代表数组中最高索引的值
const arrs = [1, 2, 3];
delete arrs[2]; // 长度依然为3
const arrs = [];
arrs[5] = 1;
console.log(arrs.length); // 6
const arrs = [1, 2, 3, 4];
arrs.length = 2; // arrs = [1, 2]
arrs.length = 0; // arrs = []
const arrs = [1, 2];
arrs.length = 5; // arrs = [1, 2,,,,]
const arrs = [1, 2, 3, 4];
arrs.length = 0; // arrs = []
let a = [1,2,3];
let b = [1,2,3];
let a1 = a;
let b1 = b;
a = [];
b.length = 0;
console.log(a, b, a1, b1); // [], [], [1, 2, 3], []
Object.assign()
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);