将新值指定给您';在javascript中的forEach循环中重复使用?
假设我有两个阵列:将新值指定给您';在javascript中的forEach循环中重复使用?,javascript,arrays,Javascript,Arrays,假设我有两个阵列: let fruits = ["Big Yellow Banana", "Big Red Apple", "Small Red Cake"]; let adj = ["Big", "Red", "Cake", "Banana"] 我想更改adj中找到的fruits中每个字符串的子字符串,并将其替换为xxx。例如,结果输出应为: ["xxx Yellow xxx", "xxx xxx Apple", "Small xxx xxx"] 这就是我所做的: let fruits
let fruits = ["Big Yellow Banana", "Big Red Apple", "Small Red Cake"];
let adj = ["Big", "Red", "Cake", "Banana"]
我想更改adj
中找到的fruits
中每个字符串的子字符串,并将其替换为xxx
。例如,结果输出应为:
["xxx Yellow xxx", "xxx xxx Apple", "Small xxx xxx"]
这就是我所做的:
let fruits = ["Big Yellow Banana", "Big Red Apple", "Small Red Cake"];
let myList = ["Big", "Red", "Cake", "Banana"];
fruits.forEach(function(part1, index1, theArray1) {
myList.forEach(function(part2, index2, theArray2) {
theArray1[index1] = theArray1[index1].replace(part2, "xxx");
});
});
我担心通过
array1[index1]
将值分配回数组是否会导致任何潜在的问题。假设我对保持原来的数组不感兴趣。 < P>你可以考虑使用<代码> map < /C>作为备选方案:
let fruits=[“大黄香蕉”、“大红苹果”、“小红蛋糕”];
让myList=[“大”、“红”、“蛋糕”、“香蕉”];
//用|连接模式,并构造一个带有全局标志的正则表达式来替换所有的正则表达式
设regex=newregexp(myList.join(“|”),“g”);
console.log(
水果.map(水果=>水果.replace(regex,'xxx'))
);代码>修改数组可能会产生意外结果。如果上面的代码是它自己的函数,那么在调用该函数后发现我的数组发生了变化将是令人惊讶的。这就是bug发生的方式
只需创建一个新数组,就可以避免这些问题。使用Array#map
和Array#reduce
返回新实体,避免Array#forEach
(这会产生副作用)
假设脚本的最大问题是客户端设备在每次运行时处理大量循环的能力;)我认为这并不能回答这个问题。
const redactedFruits = fruits.map((fruit) => {
return myList.reduce(
(redactedText, word) => redactedText.replace(word, 'xxx'),
fruit,
);
});