[英]How to replace an element in an array without changing the other elements?
If I have this array ['Jan', 'March', 'April', 'June']
.如果我有这个数组
['Jan', 'March', 'April', 'June']
。 How to replace 'April'
with 'newVal'
and keep all other elements unchanged.如何用
'newVal'
替换'April'
并保持所有其他元素不变。 I tried我试过
const months = ['Jan', 'March', 'April', 'June'];
months.splice(3, 1, 'newVal');
console.log(months);
I want it to return ['Jan', 'March', 'newVal', 'June']
but it returns ["Jan", "March", "April", "newVal"]
我希望它返回
['Jan', 'March', 'newVal', 'June']
但它返回["Jan", "March", "April", "newVal"]
Why not assign directly?为什么不直接赋值?
const months = ['Jan', 'March', 'April', 'June']; months[2] = 'newVal'; console.log(months);
You can do this:你可以这样做:
a.splice(2,1,"newVal")
It deletes 1 element at position 2 and adds the new value "newVal"它删除位置 2 处的 1 个元素并添加新值“newVal”
You could first find the Arrray.prototype.indexOf() some "string" , than you can directly replace it:你可以先找到Arrray.prototype.indexOf()一些"string" ,然后你可以直接替换它:
const arr = ["a", "b", "c", "d"];
const idx = arr.indexOf("c"); // 0..N or -1 if not found
// Make sure the index is found, than replace it
if (idx > -1) arr.splice(idx, 1, "newVal");
A nifty reusable function:一个漂亮的可重用函数:
const replaceInArray = (arr, oldVal, newVal) => { const idx = arr.indexOf(oldVal); if (idx > -1) arr.splice(idx, 1, newVal); }; const months = ['Jan', 'March', 'April', 'June']; replaceInArray(months, "April", "newVal"); console.log(months)
如果您知道要替换的值(即:您总是想替换 'April'):
months[months.indexOf("April")] = 'newVal';
永远记住数组的第一个索引总是 0,所以只需这样做:
months.splice(2,1,"newVal")
The function which you used was correct but You mistook the index value of element april
of the array months
您使用的函数是正确的,但您误认为数组
months
的元素april
的索引值
The correct index value of april is 2 4月的正确索引值为2
So your code will be like this所以你的代码会是这样的
const months = ['Jan', 'March', 'April', 'June']; months.splice(2, 1, 'newVal'); console.log(months);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.