繁体   English   中英

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

[英]Array.Splice() does not remove element at zero index when the indexed variable is checked under if condition

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

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)

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

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

if(removeableIndex)

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

if(removeableIndex != 0)

了解JavaScript如何将数字评估为布尔值很重要。 0被评估为false,所有其他数字被评估为true。

因为您的removeableIndex开头为-1,所以它将评估为true。 如果您的过滤器与索引为0的项目匹配,则其评估结果为false。

如果将默认值更改为评估为false的值,则可以解决一半的问题,但是还必须检查该值是否为0,因为这将评估为false。

var removeableIndex; // If we leave the variable undefined, it will evaluate false.
bookingStatus.bookings.filter(function(item, index) {
    if(item.id == id){
        removeableIndex = index;
        return true;
    }
    return false;
});
console.log(removeableIndex)
if(removeableIndex || removeableIndex === 0)
// If removeableIndex evaluates to true, or is equal to 0
    var result = bookingStatus.bookings.splice(removeableIndex,1);
    // remove the index

但是,您应该能够使用以下代码,因为Array.prototype.filter()根据回调函数的返回值返回一个数组。

var result = bookingStatus.bookings.filter(function(item, index) {
    return item.id !== id;
});

removeableIndex0则评估if(removeableIndex)将为false,因为0为false-y值。 因此,您应该对其进行如下评估,

if(removeableIndex >= 0)

或者要保持警惕

var removeableIndex; //Leave the removeableIndex undefined.
//... Do what you are doing
if(type of removeableIndex != "undefined" && removeableIndex >= 0)

有关JavaScript中Truthy / Falsy值的更多信息,请访问: http : //www.sitepoint.com/javascript-truthy-falsy/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM