0

次のようなスクリプトがあります。

function bakVormShipping(targetClass) {
    $.getJSON('http://shop.com/cart/?format=json', function (data) {
        $.each(data.cart.shipping.methods, function (index, methods) {
            if (index == "core|2419|36557" || index == "core|2419|36558" || index == "core|2959|31490" || index == "core|2959|31491" || index == "core|2419|36556") {
                $('<strong/>').html('€' + (+methods.price.price_incl).toFixed(2)).appendTo(targetClass);
            }
        });
    });
}

「インデックス」がいずれかのインデックスと等しくない場合、firebug で未定義または null エラーが発生します。どうすればそれを防ぐことができますか? 明らかに何かif (index == null)などがありますが、正しい方法でそれを行う方法についての手がかりがありません。

4

1 に答える 1

1

if ステートメントの上に undefined のチェックを追加します

function bakVormShipping(targetClass) {
$.getJSON('http://shop.com/cart/?format=json', function (data) {

    $.each(data.cart.shipping.methods, function (index, methods) {
        if(typeof(index) == "undefined"){
            return;
        }

        if (index == "core|2419|36557" || index == "core|2419|36558" || index == "core|2959|31490" || index == "core|2959|31491" || index == "core|2419|36556") {
            $('<strong/>').html('€' + (+methods.price.price_incl).toFixed(2)).appendTo(targetClass);
        }

    });
});

受け取ったオブジェクトに、data参照しているプロパティがあることも確認したい場合があります。data.cartdata.cart.shippingdata.cart.shipping.methods

于 2012-06-05T22:45:08.510 に答える