Javascript: Array vs Hash as array
First of all: Use array if we don't care about key or care about order, other use hash
Array
/* define */
var array = [];
/* add elements */
// by index
array[0] = 'foo';
array[1] = 'bar';
// add element at start
array.unshift('foo', 'bar'); // add two elements
// add element at the end
array.push('foo', 'bar'); // add two elements
/* delete elements */
// delete 1 element from index 0 (delete element at index 0)
array.splice(0, 1) // note that delete array[0] will set that element to undefined but array length not changed
// delete element at start
array.shift();
// delete element at the end
array.pop();
/* length */
array.length
// note if we set array[1000] = 'some thing' then array.length will be 999
// array length don't care about how much item we add but about bigest index we add.
/* loop */
for(var i = 0; i < array.length; i ++) {
// do some thing with array[i]
}
// or
for(var i in array) {
if(!array.hasOwnProperty(i)){ continue; }
// do some thing with array[i]
}
// or
array.forEach(function(value, index){
// do some thing with value and index
});
Hash
/* define */
var hash = {};
/* add elements */
// number as key
hash[1] = 'foo';
// string as key
hash['bar'] = 'foo';
// or
hash.bar = 'foo';
/* delete elements */
delete hash[1]; // delete hash.1 will give error
delete hash['bar']
// or
delete hash.bar
/* length */
// hash seem not have length method but we can use this
Object.keys(hash).length
/* loop */
for(var key in hash) {
if(!hash.hasOwnProperty(key)){ continue; }
// do some thing with hash[key] (not hash.key)
}