Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

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

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 stuff = {};
$('form input[type=checkbox]').each(function() {
    stuff[$(this).attr('value')] = $(this).attr('checked');
});

This works fine, but I'm just wondering if I can do the exact same thing with .push() method in Jquery?

I've tried something like this but it doesn't work:

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

Edit:

I was trying to use .push() method on Object, but .push() is actually just a method of Array Object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...