首页 > 解决方案 > 为什么 splice 和/或 findIndex 不允许更改数组/索引 0 的第一个元素?

问题描述

我的目标是创建一个函数,该函数将获取一个文本值,遍历一个对象数组,并删除匹配的元素。但是,我发现如果该元素是第一个实例(索引 0),则此代码不会删除该元素,并且在它确实删除的实例中,仅删除第一个匹配值而不删除任何其他值。

const cats = [{
    name: `catOne`,
    color: `orange`
}, {
    name: `catTwo`,
    color: `Grey-white`
}, {
    name: `catThree`,
    color: `Grey-white`
}] 

const deleteColor = function (arrayOfObjects, clr){

    const index = arrayOfObjects.findIndex(function(e, i){

              if (e.color.toLowerCase() === clr.toLowerCase()){   
                return i;   
              } 
          })
          if (index >= -1 ){ 
          arrayOfObjects.splice(index,1)  
          }
  }

deleteColor(cats,'grey-white')

cats.forEach(function(e, i) {
   console.log(e, i) })

输出:

{ name: 'catOne', color: 'orange' } 0
{ name: 'catThree', color: 'Grey-white' } 1

但是,如果我将文本值输入更改为“橙色”,则输出为:

{ name: 'catOne', color: 'orange' } 0
{ name: 'catTwo', color: 'Grey-white' } 1
{ name: 'catThree', color: 'Grey-white' } 2

如果我更改if (index >= -1 )输出与输入'grey-white'文本值相同。

谁能解释为什么第一个元素即使索引为 0 也没有被删除?为什么索引 -1 会导致删除索引 1?

我试着四处寻找,但找不到我要找的东西。我才刚刚开始学习香草 JS。谢谢你的帮助。

标签: javascriptarraysjavascript-objectssplice

解决方案


该方法的.findIndex()工作方式是返回回调函数为其返回值的第一个索引。换句话说,您的函数应该返回truefalse无论何时调用它,而不是它出现的索引。当true从您的函数返回时,.findIndex()将导致您返回的项目的索引true。在您的情况下,您的回调函数隐式返回undefined(这是一个快速值)或对象出现的索引。在这种情况下"orange",此对象出现在 index 处0,因此您返回0。零被认为是一个虚假值,因此 findIndex 将继续搜索。如果它没有找到任何值,它将返回-1(这是输入“橙色”时发生的情况,因此.splice(-1, 1)将删除数组中的最后一个元素)。

const cats = [{
  name: `catOne`,
  color: `orange`
}, {
  name: `catTwo`,
  color: `Grey-white`
}, {
  name: `catThree`,
  color: `Grey-white`
}]

const deleteColor = function(arrayOfObjects, clr) {
  const index = arrayOfObjects.findIndex(function(e, i) {
    return e.color.toLowerCase() === clr.toLowerCase(); 
  });
  
  if (index > -1) { // check object was found (Using > not >=)
    arrayOfObjects.splice(index, 1);
  }
}

deleteColor(cats, 'orange')

console.log(cats);

如果要删除所有具有给定颜色的猫,可以使用.filter(). 每次调用返回 true 的回调函数都会保留对象,每次调用返回 false 都会删除对象:

const cats = [{ name: `catOne`, color: `orange` }, { name: `catTwo`, color: `Grey-white` }, { name: `catThree`, color: `Grey-white` }];

const deleteColor = function(arrayOfObjects, clr) {
  return arrayOfObjects.filter(e => e.color.toLowerCase() !== clr.toLowerCase());
}

console.log(deleteColor(cats, 'grey-white'));


推荐阅读