码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-03-06 15:19:45      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:rev   ons   console   ever   asc   变调   log   pre   slice   

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']

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

标签:rev   ons   console   ever   asc   变调   log   pre   slice   

原文地址:https://www.cnblogs.com/zhongsr/p/12426516.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!