如果数组超出索引,有人可以解释下面的函数会发生什么吗?

问题描述 投票:0回答:2
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语句很好奇。

javascript arrays for-loop indexing syntax
2个回答
0
投票

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));
    }
  }
}

0
投票

仅当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; 
}
© www.soinside.com 2019 - 2024. All rights reserved.