2

以下の配列が削除されない理由。

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 が 0 より大きい場合、アイテムが削除されるとします。

小さな変更を加えた以下のコードは、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)

インデックスがゼロの場合にのみ、最初のコードセットがアイテムを削除しなかった理由を知りたいです。

4

3 に答える 3

3

インデックスがゼロの場合、この条件は false になります。

if(removeableIndex)

変数を条件全体として使用しているため、ブール値として評価されます。次と同じように機能します。

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

JavaScript が数値をブール値として評価する方法を知っておくことは重要です。0 は false として評価され、他のすべての数値は true として評価されます。

-1 から始まるため、removeableIndextrue と評価されます。フィルターがインデックス 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 値であるため、0評価は falseになります。したがって、次のように評価する必要があります。if(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 に答える