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

我有2个数组,

第一个是这样的,第二个是这样的var symbols = ['A', 'B'];var num = ['3', 'A', '5', '4'];

我需要一种方法来替换其中也存在的每个元素,以+ 10中的元素索引值替换。numsymbolssymbol

在这种情况下,我需要得到

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

如何替换所有匹配项?


ITMISS
浏览 85回答 3
3回答

哔哔one

这是非常基本的问题,所以你至少应该首先尝试自己寻找答案。但是你来了result = num.map((n) => {    const index = symbols.indexOf(n);    return index === -1 ? n : index + 10;});

catspeake

有几种方法可以做到这一点。有些比其他的更有效率。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 valuelet numsWithAllSymbolsRemoved = nums.filter(element=> symbols.indexOf(element) == -1)&nbsp;// Now numsWithAllSymbolsRemoved = ['3', '10', '5', '4']//Mutate the existing array, by index.&nbsp;for( let i = 0; i < num.length; i++){&nbsp; // If the item in num array has a index that's not -1 (if it's not found, that's what indexOf returns&nbsp; if ( symbols.indexOf(num[i]) !== -1) {&nbsp; &nbsp; nums.splice(i, 1); // Actually modify the array by splicing out the current index.&nbsp; }}&nbsp;// Now num = ['3', '10', '5', '4']

米脂

您可以尝试使用数组制作映射,其中存储元素及其相应的索引,然后使用此映射在数组中获取所需的结果。symbolssymbolMapnumlet symbolMap = new Map();symbols.forEach((symbol, index) => symbolMap.set(symbol, index));num.forEach((n, index) => {&nbsp; &nbsp; if (symbolMap.has(n)) {&nbsp; &nbsp; &nbsp; &nbsp; num[index] = symbolMap.get(n) + 10&nbsp; &nbsp; }})我在这里改变原始数组。如果您不想改变原始阵列,则可以选择使用而不是。.map().forEach()let newNum = num.map((n) => {&nbsp; &nbsp; if (symbolMap.has(n)) {&nbsp; &nbsp; &nbsp; &nbsp; return symbolMap.get(n) + 10&nbsp; &nbsp; }&nbsp; &nbsp;return n})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript