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

后端 未结 5 415
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:38

    .push() is a method of the Built-in Array Object

    It is not related to jQuery in any way.

    You are defining a literal Object with

    // Object
    var stuff = {};
    

    You can define a literal Array like this

    // Array
    var stuff = [];
    

    then

    stuff.push(element);
    

    Arrays actually get their bracket syntax stuff[index] inherited from their parent, the Object. This is why you are able to use it the way you are in your first example.

    This is often used for effortless reflection for dynamically accessing properties

    stuff = {}; // Object
    
    stuff['prop'] = 'value'; // assign property of an 
                             // Object via bracket syntax
    
    stuff.prop === stuff['prop']; // true
    
    0 讨论(0)
  • 2020-12-04 08:45

    Another way of doing it would be:

    stuff = Object.assign(stuff, {$(this).attr('value'):$(this).attr('checked')});
    

    Read more here: Object.assign()

    0 讨论(0)
  • 2020-12-04 08:55

    This is really easy: Example

    //my object
    var sendData = {field1:value1, field2:value2};
    
    //add element
    sendData['field3'] = value3;
    
    0 讨论(0)
  • 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');

    0 讨论(0)
  • 2020-12-04 09:01

    so it's easy)))

    Watch this...

        var stuff = {};
        $('input[type=checkbox]').each(function(i, e) {
            stuff[i] = e.checked;
        });
    

    And you will have:

    Object {0: true, 1: false, 2: false, 3: false}
    

    Or:

    $('input[type=checkbox]').each(function(i, e) {
        stuff['row'+i] = e.checked;
    });
    

    You will have:

    Object {row0: true, row1: false, row2: false, row3: false}
    

    Or:

    $('input[type=checkbox]').each(function(i, e) {
        stuff[e.className+i] = e.checked;
    });
    

    You will have:

    Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false}
    
    0 讨论(0)
提交回复
热议问题