gpt4 book ai didi

javascript - 在 if 条件下检查索引变量时,Array.Splice() 不会删除零索引处的元素

转载 作者:行者123 更新时间:2023-11-29 18:03:32 24 4
gpt4 key购买 nike

为什么下面的数组没有被删除。

var removeableIndex =-1;
bookingStatus.bookings.filter(function(item, index) {
if(item.id == id){
removeableIndex = index;
return true;
}
return false;
});
console.log(removeableIndex)
if(removeableIndex)
var result = bookingStatus.bookings.splice(removeableIndex,1);

我已经传递了正确的预订数组。过滤器正确匹配。当 removeableIndex 为 0 时,这不会删除项目。假设如果 removeableIndex 大于零,它将被删除。

下面的代码稍作改动即可在所有情况下正常工作,包括 removeableIndex 为 0。

var removeableIndex =-1;
bookingStatus.bookings.filter(function(item, index) {
if(item.id == id){
removeableIndex = index;
return true;
}
return false;
});
console.log(removeableIndex)
if(removeableIndex > -1)
var result = bookingStatus.bookings.splice(removeableIndex,1);

唯一的区别是if(removeableIndex > -1)

我想知道为什么第一组代码没有仅在索引为零时才删除该项目。

最佳答案

当索引为零时,此条件将为假:

if(removeableIndex)

当您将变量用作整个条件时,它将被评估为 bool 值。它的工作原理与:

if(removeableIndex != 0)

关于javascript - 在 if 条件下检查索引变量时,Array.Splice() 不会删除零索引处的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33136894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com