Arrays in javascript are indexed by numbers (or at least should be).
persons['data'].push(bob);
persons['data'].push(fill);
persons['data'].push(mark);
Using persons[2]
would give you {name: 'Mark', age: 19}.
While Javascript is so flexible that you can do as in @Sasa answer and use string indexes you may get kneecapped by other developers if you do since this is a VERY BAD PRACTICE.
[ADDED]
Consider these examples of weird and unexpected behaviour:
var ary = [];
ary[0] = false;
ary['using string indexes in javascript arrays is stupid'] = true;
console.log('pop should return the last added element', ary.pop()); // false - WTF?
console.log('lastIndexOf should be 1?', ary.lastIndexOf(true)); // -1 WTF?
Arrays in Javascript should be used as stacks. Think of a stack of cards, you either add (push) or take away cards (pull) but you don´t know which card is where (unless you´re cheating).
If you want a list of persons by name you would use an object to store persons:
persons.data = {};
persons['data']['Bob'] = bob;
Or alternatively you could filter the array to get values which match a predicate:
bob = persons.data.filter(function(person){
return person["name"] === 'Bob';
})[0];
EDIT:
Example of a function that would create or find a person:
var persons = { data : [] }
persons.data.push({ name: 'Bob', age: 10 })
// returns the index of the newly added person
persons.addOrReplace = function(new_person, attr) {
var attr = attr || 'name';
var data = this.data;
for (var i = 0; i < data.length; i++) {
if (data[i][attr] === new_person[attr]) {
data[i] = new_person;
return i;
}
}
return this.data.push(new_person);
}
persons.addOrReplace({ name: 'Bob', age: 11 });
console.log(persons.data.length); // 1
console.log(persons.data[0].age); // 11
persons.addOrReplace({ name: 'Joe', age: 11 });
console.log(persons.data.length); // 2
console.log(persons.data[persons.data.length -1].name); // Joe
Set
. – Alex Nov 2 '14 at 14:30