【问题标题】:Can someone explain what will happen in the following function if the array is out of index?如果数组超出索引,有人可以解释以下函数会发生什么吗?
【发布时间】:2020-09-20 09:36:40
【问题描述】:
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


【解决方案1】:

只有在items 内有匹配的item 的情况下才会执行return 语句。

如果item 匹配,则该函数将创建一个新数组,其中包含先前值的元素和item 的下一个值。这意味着返回数组包含来自传递数组的所有数组元素,但匹配的项目除外。

这个函数在某种意义上是有缺陷的,它不会从items 数组中删除所有item,并且当没有匹配时不会返回任何内容。

这是一个更新的版本:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 2012-11-20
      相关资源
      最近更新 更多