为了账号安全,请及时绑定邮箱和手机立即绑定

如何替换数组的所有匹配项?

如何替换数组的所有匹配项?

ITMISS 2022-09-23 17:02:18
我有2个数组,第一个是这样的,第二个是这样的var symbols = ['A', 'B'];var num = ['3', 'A', '5', '4'];我需要一种方法来替换其中也存在的每个元素,以+ 10中的元素索引值替换。numsymbolssymbol在这种情况下,我需要得到num = ['3', '10', '5', '4']如何替换所有匹配项?
查看完整描述

3 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

这是非常基本的问题,所以你至少应该首先尝试自己寻找答案。


但是你来了


result = num.map((n) => {

    const index = symbols.indexOf(n);

    return index === -1 ? n : index + 10;

});



查看完整回答
反对 回复 2022-09-23
?
catspeake

TA贡献1111条经验 获得超0个赞

有几种方法可以做到这一点。有些比其他的更有效率。


let symbols = ['A', 'B'];

let num = ['3', 'A', '5', '4'];

//Make a new array by only keeping the ones that are not found in the other array. This method does it by value

let numsWithAllSymbolsRemoved = nums.filter(element=> symbols.indexOf(element) == -1) 

// Now numsWithAllSymbolsRemoved = ['3', '10', '5', '4']


//Mutate the existing array, by index. 

for( let i = 0; i < num.length; i++){

  // If the item in num array has a index that's not -1 (if it's not found, that's what indexOf returns

  if ( symbols.indexOf(num[i]) !== -1) {

    nums.splice(i, 1); // Actually modify the array by splicing out the current index.

  }

}

 // Now num = ['3', '10', '5', '4']


查看完整回答
反对 回复 2022-09-23
?
米脂

TA贡献1836条经验 获得超3个赞

您可以尝试使用数组制作映射,其中存储元素及其相应的索引,然后使用此映射在数组中获取所需的结果。symbolssymbolMapnum


let symbolMap = new Map();

symbols.forEach((symbol, index) => symbolMap.set(symbol, index));


num.forEach((n, index) => {

    if (symbolMap.has(n)) {

        num[index] = symbolMap.get(n) + 10

    }

})

我在这里改变原始数组。如果您不想改变原始阵列,则可以选择使用而不是。.map().forEach()


let newNum = num.map((n) => {

    if (symbolMap.has(n)) {

        return symbolMap.get(n) + 10

    }

   return n

})


查看完整回答
反对 回复 2022-09-23
  • 3 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信