Adding items to an object through the .push() method

后端 未结 5 429
Happy的楠姐
Happy的楠姐 2020-12-04 08:15

I\'m doing a loop through few input elements of \'checkbox\' type. After that, I\'m adding values and checked attributes to an array. This is my code:

var st         


        
5条回答
  •  难免孤独
    2020-12-04 08:58

    stuff is an object and push is a method of an array. So you cannot use stuff.push(..).

    Lets say you define stuff as an array stuff = []; then you can call push method on it.

    This works because the object[key/value] is well formed.

    stuff.push( {'name':$(this).attr('checked')} );

    Whereas this will not work because the object is not well formed.

    stuff.push( {$(this).attr('value'):$(this).attr('checked')} );

    This works because we are treating stuff as an associative array and added values to it

    stuff[$(this).attr('value')] = $(this).attr('checked');

提交回复
热议问题