【发布时间】:2020-02-15 17:08:09
【问题描述】:
我有一个训练任务来检查数组是否与另一个数组匹配。找到的匹配项必须替换为任何值。
在一种情况下,我做到了,但使用 for...of 时出了点问题 - 我不明白为什么。
//source array
let arr = ['one', 'two', 'three', 'four', 'five', 'six'];
//array to compare
let arrForChange = ['one', 'four', 'six'];
从源数组中更改一项很容易
let changedArr = arr.map(el => { if( el === 'four'){
return el = 4;
} else {
return el = el} }
);
// console.log(changedArr); // one,two,three,4,five,six
列表上的替换更有趣一些。这里我使用.includes()
//This variant work
let cahngedArrFromList = arr.map(el => {
if(arrForChange.includes(el)){
return 'A';
} else {
return el;
}
});
// console.log(cahngedArrFromList); // A,two,three,A,five,A
寻找不同的选项更有趣。这里我使用了for...of,但出了点问题,结果不是我所期望的——只替换了第一个值。
//This variant do not work =(
let cahngedArrFromListTwo = arr.map(el => {
for (const item of arrForChange){
if (item === el){
return 'A';
} else {
return el;
}
}
});
// console.log(cahngedArrFromListTwo); // A,two,three,four,five,six
如果您删除条件else,那么一切似乎都可以正常工作......但没有
let cahngedArrFromListThree = arr.map(el => {
for (const item of arrForChange){
if (item === el){
return 'A';
} /* else {
return el;
} */
}
});
// console.log(cahngedArrFromListTree); // A,,,A,,A
你能解释一下for...of 的行为吗?还是我用错了?
【问题讨论】:
-
你
return在循环的第一次迭代中。return将立即终止循环并退出函数。将return放在循环之后,它将起作用。 -
为什么是
el = el? -
你的预期输出是什么?
标签: javascript arrays loops for-loop replace