0

I am recording acceleration data for the x-axis, so I have two values coming in - the x value, and the epoch time of the acceleration event. I want to store these as a hash, where the epoch time is the key and x-value is the value.

I created an array:

var arrX = new Array();

How can I add to it? Like this?

arrX[acceleration.timestamp] = acceleration.x
2
  • Is the timestamp a raw number? Commented Feb 27, 2012 at 0:09
  • Yes, it's a raw number like "14112123245556" so is the x value Commented Feb 27, 2012 at 0:09

3 Answers 3

1

You should use an object, which can serve as a sort of "associative array" for this application. An object will provide support for the arbitrary, non-sequential keys that you mentioned, where an array would not.

var arrX = {};

arrX[acceleration.timestamp] = acceleration.x;

More information:

Sign up to request clarification or add additional context in comments.

2 Comments

"...where an array would not" That's not exactly correct. An Array would offer the same support an Object would since an Array is a type of Object. It's just that the Array.prototype methods will only work with numeric indices. Also an Array doesn't require that the indices are sequential.
Sure, you could use an array for the job, but I think we can agree it's definitely not the most fitting data structure.
0

You can do it but without the array. Just use an object like this

var values = {};
values[acceleration.timestamp] = acceleration.x;

because if you do something like this

var x = [];
x[1555] = 500;

you will create an array of 1556 elemenets, with all elements but the 1555 set to undefined

2 Comments

Actually the x[1555] example sets x.length to 1556 because .length is always 1 higher than the highest assigned index, but it doesn't actually create any of the other elements. It's a subtle difference, but using the in operator or .hasOwnProperty() you can tell whether a particular index has been explicitly assigned undefined or just never assigned a value. The Array.forEach() method also skips over array indexes never assigned a value...
"...will create an array of 1556 elemenets" No it won't. It'll create an Array with one element, but the .length property set at 1557.
0

In Javascript if you need an associative array, you use an object:

var hash1 = {}; // declare
hash1.first = 'abc'; // set property first to a string
hash1['second'] = 'def'; // set property second to a string

var t = 'third';
hash1[t] = 'ghi'; // set property third to a string

hash1.forth = {a:1, b: 'abc'}; // set property forth to be an object / hash
                               // with 2 properties

alert (hash1.forth.a); // will alert with 1  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.