简体   繁体   English

存储值的Javascript数组

[英]Javascript arrays storing values

There might be a very simple solution my problem but just not being able to find one so please help me to get to my solution in the simplest way... 我的问题可能有一个非常简单的解决方案,但只是无法找到一个解决方案,因此请帮助我以最简单的方式获得解决方案...

The issue here is that I have data being displayed in a tabular form. 这里的问题是我的数据以表格形式显示。 Each row has 5 columns and in one of the columns it shows multiple values and so that's why I need to refer to a value by something like this row[1]['value1'], row[1]['value2'] & then row[2]['value1'], row[2]['value2']. 每行有5列,并且在其中一列中显示多个值,因此这就是为什么我需要通过诸如row [1] ['value1'],row [1] ['value2']和然后是row [2] ['value1'],row [2] ['value2']。

I declare the array 我声明数组

var parray = [[],[]];

I want to store the values in a loop something like this 我想将值存储在这样的循环中

for(counter = 0; counter < 10; counter ++){
     parray[counter]['id'] += 1;
     parray[counter]['isavailable'] += 0;
}

Later I want to loop through this and get the results: 稍后,我想循环浏览并获得结果:

for (var idx = 0; idx < parray.length; idx++) {
    var pt = {};
    pt.id = parray[schctr][idx].id;
    pt.isavailable = parray[schctr][idx].isavailable;
}

Obviously iit's not working because Counter is a numeric key and 'id' is a string key ..my question how do I achieve this ?? 显然,iit无法正常工作,因为Counter是数字键,而'id'是字符串键..我的问题我该如何实现?

Thanks for all the answers in advance. 预先感谢所有答案。

JS has no concept of "associative arrays". JS没有“关联数组”的概念。 You have arrays and objects (map). 您有数组和对象(映射)。 Arrays are objects though, and you can put keys, but it's not advisable. 数组虽然是对象,但可以放置键,但是不建议这样做。

You can start off with a blank array 您可以从一个空白数组开始

var parray = [];

And "push" objects into it 然后将物体“推”进去

for(counter = 0; counter < 10; counter++){
  parray.push({
    id : 1,
    isAvailable : 0
  });
}

Then you can read from them 然后你可以从他们那里读到

for (var idx = 0; idx < parray.length; idx++) {

  // Store the current item in a variable
  var pt = parray[idx];
  console.log(pt);

  // read just the id
  console.log(parray[idx].id);
}

Like I did here 就像我在这里一样

What you want inside your array is just a plain object: 您想要的数组内部只是一个普通对象:

// just a regular array
var parray = [];

for(var counter = 0; counter < 10; counter++){
  // create an object to store the values
  var obj = {};
  obj.id = counter;
  obj.isavailable = 0;
  // add the object to the array
  parray.push(obj);
}

later: 后来:

for (var idx = 0; idx < parray.length; idx++) {
  var pt = parray[idx];
  // do something with pt
}

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

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