JavaScript数组方法: 变异方法 (mutation method)和非变异 (non-mutating method)

JavaScript提供了几种添加,删除和替换数组中项目的方法。但是其中一些方法会使数组发生变化,而另一些则是不发生变化的。他们产生一个新的数组。

变异方法 (mutation method)

push()、pop()、shift()、unshift()、splice()、sort()、reverse() 等, 都会改变调用了这些方法的原始数组。
如:

const mutatingArr = ['a',' b', 'c']
mutatingArr.push('d');   //['a', 'b', 'c', 'd']
mutatingArr.unshift('e');   //['e', 'a', 'b', 'c', 'd']
console.log(mutatingArr);  //['e', 'a', 'b', 'c', 'd']

非变异 (non-mutating method)

filter()、concat()、slice()、map() 调用这些方法不会改变原始数组,而是返回一个新的数组。
如:

const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = arr1.concat('f'); // ['a', 'b', 'c', 'd', 'e'. 'f']
console.log(arr1); // ['a', 'b', 'c', 'd', 'e']
原文地址:https://www.cnblogs.com/zhongsr/p/12426516.html