通过.push()方法将对象添加到对象 [英] Adding items to an object through the .push() method

查看:704
本文介绍了通过.push()方法将对象添加到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过'checkbox'类型的几个输入元素进行循环。之后,我将值和检查属性添加到数组中。这是我的代码:

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');
});

这很好用,但我只是想知道我是否能用.push做同样的事情Jquery中的()方法?

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')} );

修改:

我试图在Object上使用.push()方法,但.push()实际上只是一个Array Object的方法。

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

推荐答案

.push() 内置数组对象

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

它与jQuery无任何关系。

It is not related to jQuery in any way.

您正在定义文字对象

// Object
var stuff = {};

您可以像这样定义文字数组

You can define a literal Array like this

// Array
var stuff = [];

然后

stuff.push(element);






数组实际上得到括号语法 stuff [index] 继承自其父对象。这就是为什么你能够像第一个例子那样使用它。


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

这篇关于通过.push()方法将对象添加到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆