3 回答
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;
});
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']
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
})
添加回答
舉報(bào)
