简体   繁体   English

使用INDEX添加到数组或对象

[英]Add to array or object with INDEX

how can i generate array or object with own index? 如何生成具有自己索引的数组或对象?

in php i can: 在PHP中我可以:

$array = array();

foreach($users as $user){
   $array[$user] = $user;
} 

and in jQuery? 在jQuery中?

var arr = new Array();
$('input').each(function(){
   arr[$(this).val()] = $(this).val();
})

i would like use JS Object for this, but how? 我想为此使用JS对象,但是如何?

var arr = {};
$('input').each(function(){
    ...

That's all you need. 这就是您所需要的。 In JavaScript, arrays ( new Array() or [] ) have consecutive indexes while objects ( new Object() or {} ) have arbitrary properties. 在JavaScript中,数组( new Array()[] )具有连续索引,而对象( new Object(){} )具有任意属性。

this is originally not possible via arrays in but there is a way through which u can achieve it with JS objects 最初这不可能通过数组实现,但是有一种方法可以通过JS对象实现

var person = { country: 'Pakistan' };

now this is an object U will see that both these statements gives same result. 现在这是一个对象U,您将看到这两个语句给出相同的结果。

alert( person.country );
alert( person['country'] );

Now this means actually it is object, but it also acts like array. 现在,这实际上意味着它是对象,但它也像数组一样起作用。

Just use an object instead of an array: 只需使用对象而不是数组即可:

var obj = {};
$('input').each(function() {
    obj[$(this).val()] = $(this).val();
})
var obj = {};
$('input').each(function(){
   obj[$(this).val()] = $(this).val();
});

It's basically this simple. 基本上就是这么简单。 After this, you can access them either by obj[value] or obj.value . 之后,您可以通过obj[value]obj.value来访问它们。

使用对象而不是数组

var arr = {};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM