简体   繁体   English

Javascript数组对象数组

[英]Javascript array object arrays

THis is going to sound like a stupid question but here it goes. 这听起来像是一个愚蠢的问题,但事实确实如此。 I have a js array formatted like so 我有一个像这样格式化的js数组

 var locationID = [
              { ID: "ID1", location: "location1" },
              { ID: "ID2", location: "location2" },
              { ID: "ID3", location: "location3" },
   ];

I am trying to loop through the array 我正在尝试遍历数组

for(i = 0; i < locationID.length;i++){
   var object = locationID[i];
}

I want to get both elements from the inner array so the ID and location. 我想从内部数组中获取两个元素,以便获取ID和位置。 would I do this by object[0] or object["ID"] for example. 我会通过object[0]object["ID"]来做到这一点。

Also is there a more efficient way to do what I need to do like a for each loop or something along those lines. 还有一种更有效的方式来完成我需要做的事情,例如对每个循环或沿这些方向的东西。

Use object.ID or object['ID'] . 使用object.IDobject['ID']

Objects {} in JavaScript are associative, or named arrays. JavaScript中的对象 {}是关联数组或命名数组。 (Also known as a map in many languages. They are indexed by strings (in this case). (在许多语言中也称为地图。它们通过字符串索引(在这种情况下)。

Arrays [] , are indexed by integral numbers, starting from 0 and counting up to n-1 , where n is the length of the array. 数组 []由整数索引,从0开始到n-1为止,其中n是数组的长度。

If you want to programmatically go through all the (key, value) pairs in each object, you can use this method . 如果要以编程方式遍历每个对象中的所有(键,值)对,则可以使用此方法

Quotations (String Literals) 引号(字符串文字)

To reiterate my comment below about single and double quotes: 在下面重申我对单引号和双引号的评论:

If you're talking about inside the [] , no [,they're not important]. 如果您在[]内谈论,则[] [不重要]]。 JavaScript treats single quotes and double quotes pretty much the same . JavaScript处理单引号和双引号几乎相同 Both of them denote string literals. 它们都表示字符串文字。 Interestingly, you can use single quotes inside double quotes or vice-versa: "I wanted to say 'Hello world!'" would be a (single) valid string, but so would 'But I accidentally said "Goodbye" . 有趣的是,您可以在双引号中使用单引号,反之亦然: "I wanted to say 'Hello world!'"将是(单个)有效字符串,但是也会这样,但'But I accidentally said "Goodbye"

This is an optimized loop based from the book of Nicholas Zackas (YAHOO performance chief). 这是根据Nicholas Zackas(YAHOO性能负责人)的书而优化的循环。 I am performing a cached array length to prevent re-evaluation of array length on every iteration of the loop. 我正在执行缓存的数组长度,以防止在每次循环迭代时重新评估数组长度。 Please check jsperf.com. 请检查jsperf.com。 Also, native loop is always faster than method based loops jQuery.each and Array.prototype.forEach. 而且,本机循环总是比基于方法的循环jQuery.each和Array.prototype.forEach更快。 This is also supported on browsers below ie8 ie8以下的浏览器也支持此功能

    var currentItem,
        locationInfo = [
          { ID: "ID1", location: "location1" },
          { ID: "ID2", location: "location2" },
          { ID: "ID3", location: "location3" },
        ];

    for (var i = 0, len = locationInfo.length; i < len; i++) {
        currentItem = locationInfo[i];

        console.log(currentItem.ID);//I prefer this because it shrinks down the size of the js file
        console.log(currentItem["ID"]);
    }

what you have already will return each of the objects in the JSON as you run the loop. 运行循环时,已经拥有的将返回JSON中的每个对象。 What you need is something like 您需要的是类似

for(i = 0; i < locationID.length;i++){
   var object = {locationID[i].ID, locationID[i].location};
}

Remember properties of objects are accessed by their keys since they are key-value pairs. 请记住,对象的属性是通过键值访问的,因为它们是键值对。

You can use the forEach method, which make your code more cleaner. 您可以使用forEach方法,从而使您的代码更清晰。

See forEach 每个

locationID.forEach(function(elm){
  //Here, elm is my current object
  var data = elm;
  console.log(data.ID):
  console.log(data.location);
});

EDIT : Then for your second question, you should filter and map methods. 编辑:然后对于第二个问题,您应该过滤映射方法。

function findNamebyID(id){
  //Filter by id and map the data to location
  return locationID.filter(function(elm){
    return elm.ID === id;
  }).map(function(elm){
    return elm.location;
  })
}

For loops are going to be your best bet as far as speed, here's how you'd do it with forEach (IE 9+) 就速度而言,for循环将是您最好的选择,这是使用forEach(IE 9+)的方法

locationID.forEach(function(location, i){
    console.log(location['ID'])
    console.log(location['location'])
});

jQuery make's it a little easier but runs slower jQuery使它变得更简单但运行更慢

$.each(array, function(i, item){

});

http://jsperf.com/for-vs-foreach/75 http://jsperf.com/for-vs-foreach/75

Also here a useful link: For-each over an array in JavaScript? 这里还有一个有用的链接: 在JavaScript中对数组进行逐个调用?

Something as: 如:

var location = locationID.reduce(function(ob, cur) {
ob[cur.ID] = cur.location;
return ob;
}, {});

The result you get is: 您得到的结果是:

Object {ID1: "location1", ID2: "location2", ID3: "location3"}

Meaning you can do: 这意味着您可以:

location.ID1 // location1
location.ID2 // location2
...

an alternative to your loop, would be to use the JavaScript for (.. in ..) since you aren't really using the iterator; 循环的一种替代方法是将JavaScript for (.. in ..)因为您实际上并未使用迭代器; it just adds fluff 它只会增加绒毛

for(i = 0; i < locationID.length;i++){
   var object = locationID[i];
}

could be written as: 可以写成:

for (item in locationID) {
  var object = item;
}

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

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