为什么 splice and/or findIndex 不允许更改 array/index 0 的第一个元素?

Why does splice and/or findIndex not allow a change to the first element of an array/index 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

但是如果我将输入的文本值更改为'orange',则输出为:

{ 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?

我试着四处搜索,但找不到我要找的东西。我才刚刚开始学习 vanilla JS。感谢您的帮助。

方法.findIndex() works is by returning the first index which the callback function returns a truthy value for. In other words, your function should return true or false whenever it is called, not the index at which it appears. When true is returned from your function, .findIndex() will result in the index of the item you returned true for. In your case, your callback function implicitly returns undefined (which is a fasly值的方式)或对象出现的索引。在 "orange" 的情况下,此对象出现在索引 0 处,因此您 return 0。零被认为是虚假值,因此 findIndex 将继续其搜索。如果它没有找到任何值,它将 return -1 (这是输入 "orange" 时发生的情况,因此 .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()。每次调用 returns true 的回调函数将保留对象,每次调用 returns 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'));