更新时间:2023-01-31 11:11:42
您可以使用哈希表并检查。如果字符串未包含在哈希表中,则为该元素设置替换值。
You could use a hash table and check against. If the string is not included in the hash table, a replacement value is set for this element.
var array1 = ['a','b','c','d'],
array2 = ['d','v','n','a','i','f'],
array3 = ['1','2','3','4','5','6'],
hash = Object.create(null);
array1.forEach(function (a) {
hash[a] = true;
});
array2.forEach(function (a, i, aa) {
if (hash[a]) {
aa[i] = array3[i];
}
});
console.log(array2);
ES6, 设置
ES6 with Set
var array1 = ['a','b','c','d'],
array2 = ['d','v','n','a','i','f'],
array3 = ['1','2','3','4','5','6'];
array2.forEach((hash => (a, i, aa) => {
if (hash.has(a)) {
aa[i] = array3[i];
}
})(new Set(array1)));
console.log(array2);