替换数组中特定位置的元素而不对其进行更改 [英] Replace element at specific position in an array without mutating it

查看:46
本文介绍了替换数组中特定位置的元素而不对其进行更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不更改数组的情况下完成以下操作:

How can the following operation be done without mutating the array:

let array = ['item1'];
console.log(array); // ['item1']
array[2] = 'item2'; // array is mutated
console.log(array); // ['item1', undefined, 'item2']

在上面的代码中,对 array 变量进行了突变.如何在不更改数组的情况下执行相同的操作?

In the above code, array variable is mutated. How can I perform the same operation without mutating the array?

推荐答案

您可以使用 Object.assign :

Object.assign([], array, {2: newItem});

这篇关于替换数组中特定位置的元素而不对其进行更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆