function remove(items, item){
for (let i =0; i < items.length; i++) {
if (items[i] === item){
return [ ...items.slice(0, i), ...items.slice(i+1)]
}
}
}
我的代码在上面。我对return语句很好奇。
function remove(items, item) {
for (let i = 0; i < items.length; i++) {
if (items[i] === item) {
return items.slice(0, i).concat(items.slice(i + 1, items.length));
}
}
}
仅当item
中存在items
匹配的情况时,才会执行return语句。
如果item
匹配,则该函数将创建一个新数组,该数组由item
的先前值和后续值的元素组成。这意味着return数组包含传递的数组中除匹配项之外的所有数组元素。
此函数在一定意义上是有缺陷的,它不会从item
数组中删除所有的items
,并且在没有匹配项时不会返回任何内容。
这里是更新版本:
function remove(items, item) {
let newItems = [];
for (let i = 0; i < items.length; i++) {
if (items[i] !== item) {
// if current item is not equal to searching item, than it
// should be in the returned array.
newItems.push(items[i];
}
// you should not return if there is match, in that case multiple
// matching item would not be removed from items array
}
// always return the result array whether there is a match or not.
return newItems;
}