javascript - 为什么 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。谢谢你的帮助。
解决方案
该方法的.findIndex()
工作方式是返回回调函数为其返回真值的第一个索引。换句话说,您的函数应该返回true
或false
无论何时调用它,而不是它出现的索引。当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'));
推荐阅读
- ssh - 在启动 VNC 会话时询问我第二个“密码”时,MobaXterm 是什么意思?
- php - 如何在 Laravel 8 中的控制器和刀片模板中创建所需的下拉选择字段
- react-native - React native - 如何在所有子视图完成渲染后知道视图的高度?
- java - 来自 Java 的 Runtime.getRuntime.exec 139 (SIGSEGV) 用于 C 程序
- laravel - DateTime::__construct():无法在位置 0 (2) 解析时间字符串 (22/03/1983):意外字符
- javascript - 如何在 useEffect() React Hook 中使用 await 关键字
- apache-nifi - 如何从 nifi 中的 csv 文件中删除重复的列
- linux - 读取输入而不指定输入长度
- c# - 使自托管 WCF 数据服务主机名感知
- java - 在 main 方法中使用 SwingUtilities.invokeLater()