第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何替換數(shù)組的所有匹配項(xiàng)?

如何替換數(shù)組的所有匹配項(xiàng)?

ITMISS 2022-09-23 17:02:18
我有2個(gè)數(shù)組,第一個(gè)是這樣的,第二個(gè)是這樣的var symbols = ['A', 'B'];var num = ['3', 'A', '5', '4'];我需要一種方法來(lái)替換其中也存在的每個(gè)元素,以+ 10中的元素索引值替換。numsymbolssymbol在這種情況下,我需要得到num = ['3', '10', '5', '4']如何替換所有匹配項(xiàng)?
查看完整描述

3 回答

?
嗶嗶one

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊

這是非常基本的問(wèn)題,所以你至少應(yīng)該首先嘗試自己尋找答案。


但是你來(lái)了


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

    const index = symbols.indexOf(n);

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

});



查看完整回答
反對(duì) 回復(fù) 2022-09-23
?
catspeake

TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊

有幾種方法可以做到這一點(diǎn)。有些比其他的更有效率。


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']


查看完整回答
反對(duì) 回復(fù) 2022-09-23
?
米脂

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊

您可以嘗試使用數(shù)組制作映射,其中存儲(chǔ)元素及其相應(yīng)的索引,然后使用此映射在數(shù)組中獲取所需的結(jié)果。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

    }

})

我在這里改變?cè)紨?shù)組。如果您不想改變?cè)缄嚵?,則可以選擇使用而不是。.map().forEach()


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

    if (symbolMap.has(n)) {

        return symbolMap.get(n) + 10

    }

   return n

})


查看完整回答
反對(duì) 回復(fù) 2022-09-23
  • 3 回答
  • 0 關(guān)注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)