前端⾯试:js数组合并的⽅法
⾯试原题是,将新数组加到旧数组后⾯,有哪些⽅法?
1、concat( )
返回拼接后的数组,不改变原数组,它不是直接附加到现有数组上,⽽是返回⼀个新数组,并把这个数组赋值给arr1才能达到⽬的。
var arr1 =[0,1,2];
var arr2 =[5,6,7];
arr1 = at(arr2)
console.log(arr1);// [0,1,2,5,6,7]
2、forEach
官⽅描述是,forEach()被调⽤时,不会改变原数组,也就是调⽤它的数组(尽管callback 函数在被调⽤时可能会改变原数组)。
(译注: 此处说法可能不够明确,具体可参考EMCA语⾔规范: ’ forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn’, 即forEach不会直接改变调⽤它的对象,但是那个对象可能会被callback 函数改变。)
var arr1 =[0,1,2];
let arr =[];
arr1.forEach((value)=> arr.push(value));
arr.push(88);// 添加新项以证明不会修改原始数组
console.log(arr);// [0, 1, 2,88]
console.log(arr1);// [0, 1, 2]
那么哪些情况下使⽤forEach会改变原数组呢?要满⾜两个条件
1、你要操作的那些数组元素是⼀个引⽤类型的数据,即可能是数组、对象、函数(函数是引⽤类型)。
2、forEach⾥的回调函数对引⽤类型的数组元素的属性有修改操作。
上⾯两条总结⼀下就是,还是上⾯的例⼦,你是直接修改整个元素,⽽不是修改该元素的某个属性,那么原数组也不会被改变。
看以下例⼦:
var people =[{ name:"⾦⾓"},{ name:"银⾓"},{ name:"⼋戒"}];
people.forEach((item)=>{
item ={ name:"我"};
});
console.log(people);// [{name: "⾦⾓"}, {name: "银⾓"}, {name: "⼋戒"}]
这⾥涉及到深拷贝和浅拷贝,后⾯再慢说。
3、map
var arr1 =[0,1,2];
var arr = arr1.map( num => num);
arr.push(3);// 添加新项以证明不会修改原始数组
console.log(arr);// [0, 1, 2, 3]
console.log(arr1);// [0, 1, 2]
4、经典的apply
var arr1 =[0,1,2];
var arr2 =[];
Array.prototype.push.apply(arr2, arr1);
arr2.push(4)
console.log(arr2);//[0, 1, 2, 4]
console.log(arr1);//[0, 1, 2]
5、for循环
for(var i =0; i < arr1.length; i++){
arr2.push(arr1[i]);
}
arr2.push(4)// 添加新项以证明不会修改原始数组console.log(arr2);//[0, 1, 2, 3, 4]
console.log(arr1);//[0, 1, 2, 3]
6、slice
var arr1 =[0,1,2,3];
var arr2 = arr1.slice();
arr2.push(4)
console.log(arr2);//[0, 1, 2, 3, 4]
console.log(arr1);//[0, 1, 2, 3]
7、from
var arr1 =[0,1,2,3];
var arr2 = Array.from(new Set(arr1));
arr2.push(4)
console.log(arr2);//[0, 1, 2, 3, 4]
console.log(arr1);//[0, 1, 2, 3]
8、扩展运算符[…]
var arr1 =[0,1,2,3];
var arr2 =[...arr1];
arr2.push(4)
console.log(arr2);//[0, 1, 2, 3, 4]
console.log(arr1);//[0, 1, 2, 3]
9、Array.of 和扩展运算符[…]
var arr1 =[0,1,2,3];
var arr2 = Array.of(...arr1);
arr2.push(4)
console.log(arr2);//[0, 1, 2, 3, 4]
console.log(arr1);//[0, 1, 2, 3]
10、Array构造函数和扩展运算符[…]
var arr1 =[0,1,2,3];
var arr2 =new Array(...arr1);
arr2.push(4)
console.log(arr2);//[0, 1, 2, 3, 4]
console.log(arr1);//[0, 1, 2, 3]
11、使⽤解构
var arr1 =[0,1,2,3];
var[...arr2]= arr1;
arr2.push(4)
console.log(arr2);//[0, 1, 2, 3, 4]
console.log(arr1);//[0, 1, 2, 3]
js数组方法总结12、push
arr2.push(...arr1);
arr2.push(4);
console.log(arr2);//[0, 1, 2, 3, 4] console.log(arr1);//[0, 1, 2, 3]
13、unshift
var arr1 =[0,1,2,3];
var arr2 =[];
arr2.unshift(...arr1);
arr2.push(4);
console.log(arr2);//[0, 1, 2, 3, 4] console.log(arr1);//[0, 1, 2, 3]
14、reduce
var arr1 =[0,1,2,3];
var arr2 = duce((acc, x)=>{ acc.push(x);
return acc;
},[]);
arr2.push(4);
console.log(arr2);//[0, 1, 2, 3, 4] console.log(arr1);//[0, 1, 2, 3]
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论