2

Why below array is not being removed.

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);

I have passed the correct array of bookings. Filter is correctly matching. This does not remove item when removeableIndex is 0. Suppose if removeableIndex is grater than zero it is being removed.

Below code with small change works correctly for all cases including removeableIndex is 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);

Only difference is that if(removeableIndex > -1)

I would like to know why didnt the first set of code did not remove the item only when it is at zero index.

4

3 回答 3

3

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

if(removeableIndex)

当您将变量用作整个条件时,它将被评估为布尔值。它的工作原理与以下相同:

if(removeableIndex != 0)
于 2015-10-14T23:08:31.157 回答
1

了解 JavaScript 如何将数字评估为布尔值非常重要。0 被评估为假,所有其他数字被评估为真。

因为您removeableIndex从 -1 开始,所以它将评估为真。如果您的过滤器与索引 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;
});
于 2015-10-14T23:28:24.167 回答
0

什么时候评估将是错误的,因为removeableIndex是一个 false-y 值。所以,你应该如下评估它,0if(removeableIndex)0

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/

于 2015-10-14T23:54:20.343 回答