为什么splice和/或findIndex不允许更改数组/索引0的第一个元素?

问题描述 投票:0回答:1

我的目标是创建一个函数,该函数将获取文本值,循环访问对象数组,并删除匹配的元素。但是,我发现如果此代码是第一个实例(索引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?

我试图四处搜寻,但找不到我想要的东西。我才刚刚开始学习香草JS。感谢您的帮助。

arrays foreach javascript-objects splice
1个回答
0
投票

.findIndex()方法的工作方式是通过返回第一个索引,回调函数为其返回一个truthy值。在您的情况下,您的回调函数隐式返回undefined(这是fasly值)或对象以给定名称出现的索引。在"orange"的情况下,此对象出现在索引0上,因此您返回0。零被认为是虚假的值,因此findIndex将继续其搜索。如果找不到任何值,它将返回-1

© www.soinside.com 2019 - 2024. All rights reserved.