Javascript - 创建数组索引和访问

时间:2022-06-22 04:19:15

I am looking to create a simple array using a time stamp for the index so that I can access the values by timestamp without iterating through the array, however I am struggling!

我正在寻找使用索引的时间戳创建一个简单的数组,以便我可以通过时间戳访问值而无需遍历数组,但我正在努力!

I need to be able to set 2 values for each row.

我需要能够为每一行设置2个值。

For example:

例如:

var myarray = [];
var test1 = 'hello'
var test2 = 'world'

myarray[timestamp] = [test1, test2];

So for a given timestamp e.g. 12345678, how could I access the value of test2?

因此,对于给定的时间戳,例如12345678,我怎样才能访问test2的值?

Appreciate any thoughts and advice.

欣赏任何想法和建议。

Regards, Ben.

问候,本。

2 个解决方案

#1


7  

If you use an array that way, you'll end up with an array containing a large amount of undefined values:

如果以这种方式使用数组,最终会得到一个包含大量未定义值的数组:

var myarr = [];
myarr[1000] = 'hello';
console.log(myarr.length); //=> 1001 
console.log(myarr[0]); //=> undefined
console.log(myarr[999]); //=> undefined

So, you may want to use an object for that and use some kind of sorting. For example

因此,您可能希望使用一个对象并使用某种排序。例如

var myobj = {}, timestamp = new Date().getTime();
myobj[timestamp] =   ['hello','world'];
myobj[timestamp+1] = 'how are we today?';

function retrieveSorted(obj){
  var keys = Object.keys(obj).sort(), key, ret = [];
  while(key = keys.shift()){
    ret.push(obj[key]);
  }
  return ret;
}

var sorted = retrieveSorted(myobj); 
   //=> [["hello", "world"], "how are we today?"]
myobj[timestamp][1]; //=> world

#2


2  

myarray[timestamp][1]

1 is the 2nd index in inner array. Indexes start from 0.

1是内部数组中的第二个索引。索引从0开始。

#1


7  

If you use an array that way, you'll end up with an array containing a large amount of undefined values:

如果以这种方式使用数组,最终会得到一个包含大量未定义值的数组:

var myarr = [];
myarr[1000] = 'hello';
console.log(myarr.length); //=> 1001 
console.log(myarr[0]); //=> undefined
console.log(myarr[999]); //=> undefined

So, you may want to use an object for that and use some kind of sorting. For example

因此,您可能希望使用一个对象并使用某种排序。例如

var myobj = {}, timestamp = new Date().getTime();
myobj[timestamp] =   ['hello','world'];
myobj[timestamp+1] = 'how are we today?';

function retrieveSorted(obj){
  var keys = Object.keys(obj).sort(), key, ret = [];
  while(key = keys.shift()){
    ret.push(obj[key]);
  }
  return ret;
}

var sorted = retrieveSorted(myobj); 
   //=> [["hello", "world"], "how are we today?"]
myobj[timestamp][1]; //=> world

#2


2  

myarray[timestamp][1]

1 is the 2nd index in inner array. Indexes start from 0.

1是内部数组中的第二个索引。索引从0开始。