3 回答
TA贡献1854条经验 获得超8个赞
这是非常基本的问题,所以你至少应该首先尝试自己寻找答案。
但是你来了
result = num.map((n) => {
const index = symbols.indexOf(n);
return index === -1 ? n : index + 10;
});
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']
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
})
添加回答
举报