Javascript - create array index and access - Stack Overflow

I am looking to create a simple array using a time stamp for the index so that I can access the values

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.

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?

Appreciate any thoughts and advice.

Regards, Ben.

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.

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?

Appreciate any thoughts and advice.

Regards, Ben.

Share Improve this question asked Apr 28, 2012 at 11:54 BenBen 6,08611 gold badges52 silver badges73 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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
myarray[timestamp][1]

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743700134a4492427.html

相关推荐

  • Javascript - create array index and access - Stack Overflow

    I am looking to create a simple array using a time stamp for the index so that I can access the values

    6天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信