如何在数组中使用特定索引搜索值并修改其值? [英] how to search for the value with a certain index in an array and modify its value?
问题描述
我有两个数组,第一个包含两个数字,第二个包含12个值.
I have two arrays, the first contains two numbers and the second 12 values.
firstArray = [0, 6];
secondArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
我想获取第一个数组的数字,并检查第二个数组的索引是否匹配,然后更改匹配的值.
I want to take the numbers of the first array and and check that index of the second array matches and then change the value of the matching ones.
在这种情况下,输出将是
In this case the output would be
secondArray = ["blank", "February", "March", "April", "May", "June", "blank", "August", "September", "October", "November", "December"];
我试图进行for循环以获取firstArray中的值,但我正在获取索引而不是值
I was trying to for-loop for getting the values in firstArray but I'm gettin the indexes and not the value
for (let i = 0; i < this.state.lastIndex.length; i++) {
}
干草我该怎么做?有什么方法可以使它比使用for循环更直接?
hay How can I do it? Is there any way to make it more direct than with a for-loop?
感谢您的帮助
推荐答案
对于oneliner,您可以使用 Array.prototype
中的map:
For a oneliner, you could use map from Array.prototype
:
secondArray = secondArray.map((element, index) => firstArray.includes(index) ? "blank" : element )
请注意,map函数返回一个新数组,而不是修改原始数组.
Please note the map function returns a new array, instead of modifying the original one.
删除了多余的 return
和箭头函数主体周围的花括号
removed redundant return
and curly-braces around the arrow function body
这篇关于如何在数组中使用特定索引搜索值并修改其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!