问题描述
我正在对复选框"类型的几个输入元素进行循环.之后,我将值和检查的属性添加到数组中.这是我的代码:
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');
});
这很好用,但我只是想知道我是否可以用 Jquery 中的 .push() 方法做完全相同的事情?
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')} );
我试图在对象上使用 .push() 方法,但 .push() 实际上只是一个数组对象的方法.
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
它与 jQuery 没有任何关系.
It is not related to jQuery in any way.
您正在使用
// Object
var stuff = {};
您可以像这样定义文字数组
// Array
var stuff = [];
然后
stuff.push(element);
数组实际上从它们的父对象 Object 继承了它们的括号语法 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() 方法向对象添加项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!