简体   繁体   中英

Strange undefined jquery error

I am trying to itterate trough a jquery array, and I am having an error The script causing the error is:

$.each(amount, function (key, value) {
    console.info('>>> Selected line: '+value.value + " " + value.currency);
    if ((value.currency == currency) && (value.value == val)) {
        amount.splice(key,1);
        console.info('Deleted: [' + value.value + " " + value.currency+ "] from line "+ key);
    }
});

The error firebug throws is:

TypeError: value is undefined

Could someone point me where the error is or how to fix the error?

The issue is with your .splice() . When you remove item 0, everything moves up a spot, so you no longer have an item 1.

Generally speaking, you can't remove items from a list you're enumerating (unless taking steps to adjust the current index when adding or removing items, but.. yuck).

I would recommend using a filter function like grep instead:

http://jsfiddle.net/DnN4a/

var newArr = $.grep(amount, function(item, idx) {
   return item.currency == currency || item.value == val; 
}, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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