我正在通过几个"checkbox"类型的输入元素进行循环.之后,我将向数组添加值和已判断属性.这是我的代码:

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.

推荐答案

.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.

这通常用于动态访问属性的轻松反射

stuff = {}; // Object

stuff['prop'] = 'value'; // assign property of an 
                         // Object via bracket syntax

stuff.prop === stuff['prop']; // true

Jquery相关问答推荐

更改后如何使用 jQuery Select CSS 类

如何用 jQuery / AJAX 替换表格的行

为什么 .join() 不能与函数参数一起使用?

自动完成时触发的任何事件?

如何滚动到jQuery中的元素?

jQuery 与 ExtJS

JSLint 消息:未使用的变量

JavaScript / jQuery:测试窗口是否有焦点

如何在 jQuery 中为 getJSON 设置缓存 false?

如何使用 jquery 更改 onclick 事件?

如何从表格单元格 (td) 中获取相应的表格标题 (th)?

如何触发href元素的点击事件

jQuery:value.attr 不是函数

Javascript 使用哈希值重新加载页面

测试两个元素是否相同

jQuery 按值 Select 选项元素

如何使用 jQuery 在悬停时显示工具提示消息?

将多个 JavaScript 文件合并为一个 JS 文件

javascript jquery单选按钮单击

Twitter Bootstrap alert 消息关闭并再次打开