js 改变原数组和不改变原数组的方法整理

let arr = [‘a’, ‘b’, ‘c’, ‘d’]

改变原数组的:

1、 shift:将第一个元素删除并且返回删除元素,空即为undefined
let a = arr.shift()
console.log(a) // a
console.log(arr) // [‘b’, ‘c’, ‘d’]

2、unshift:向数组开头添加元素,并返回新的长度
let a = arr.unshift(0)
console.log(a) // 5 返回数组长度
console.log(arr) // [0, ‘a’, ‘b’, ‘c’, ‘d’]

3、pop:删除最后一个并返回删除的元素
let a = arr.pop()
console.log(a) // d
console.log(arr) // [‘a’, ‘b’, ‘c’]

4、push:向数组末尾添加元素,并返回新的长度
et a = arr.push(‘f’)
console.log(a) // 5 返回数组长度
console.log(arr) // [‘a’, ‘b’, ‘c’, ‘d’, ‘f’]

5、reverse:颠倒数组顺序
let a = arr.reverse()
console.log(a) // [“d”, “c”, “b”, “a”]
console.log(arr) // [“d”, “c”, “b”, “a”]

6、sort:对数组排序
let arr = [‘c’, ‘a’, ‘d’, ‘b’]
let a = arr.sort()
console.log(a) // [‘a’, ‘b’, ‘c’, ‘d’]
console.log(arr) // [‘a’, ‘b’, ‘c’, ‘d’]

7、splice:splice(start,length,item)删,增,替换数组元素,返回被删除数组,无删除则不返回
let a = arr.splice(1, 2, ‘f’)
console.log(a) // 返回被删除的元素数组[‘b’, ‘c’]
console.log(arr) // 在添加的地方添加元素后的数组[“a”, “f”, “d”]

8、copyWithin:方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。
let a = arr.copyWithin(1, 2,3)
console.log(a) //返回被复制的元素数组 [‘a’, ‘c’, ‘c’, ‘d’]
console.log(arr) //原元素数组已经改变 [‘a’, ‘c’, ‘c’, ‘d’]

9、fill:用一个元素填充原来的数组
let a = arr.fill(‘e’, 2, 4);
console.log(a) // 返回它会改变调用它的 this 对象本身, 然后返回它[‘a’, ‘b’, ‘e’, ‘e’]
console.log(arr) // [‘a’, ‘b’, ‘e’, ‘e’]

10、map: 只有当arr为基本数据类型时,map方法才不会改变原始数组,arr为引用类型时,还是会改变原数组的
const citys = [{ name: ‘shenzhen’ }, { name: ‘hanghzhou’ }];
const newCitys = citys.map((item) => {
item.country = ‘china’;
return item;
});
console.log(‘citys’, citys); //[{ name: ‘shenzhen’, country: ‘china’ },{ name: ‘hanghzhou’, country: ‘china’ }]
console.log(‘newCitys’, newCitys); //[{ name: ‘shenzhen’, country: ‘china’ },{ name: ‘hanghzhou’, country: ‘china’ }]

不改变原数组的:

1、concat:targetArr.concat(otherArr[,anyOtherArr])连接多个数组,返回新的数组
let a = arr.concat([‘e’, ‘f’])
console.log(a) // 新数组 [“a”, “b”, “c”, “d”, “e”, “f”]
console.log(arr) // [“a”, “b”, “c”, “d”] 不变

2、join:将数组中所有元素以参数作为分隔符放入一个字符
let a = arr.join(‘-’)
console.log(a) // 字符串 a-b-c-d
console.log(arr) // [“a”, “b”, “c”, “d”] 不变

3、slice:slice(start,end),返回选定元素
let a = arr.slice(1)
console.log(a) // [“b”, “c”, “d”]
console.log(arr) // [“a”, “b”, “c”, “d”] 不变

4、filter,forEach,some,every,reduce等不改变原数组 map一个基本类型数组时

「转载」作者:HarveyT
链接:https://juejin.cn/post/6844904192671219719
来源:稀土掘金

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值