consider the following:
var service_call_array = {
3 : 'test',
4 : 'more of a test eh?',
5 : 'more info required'
};
I can loop through it thus
$(function() {
$.each(service_call_array, function(key, value) {
alert(key + ':' +value);
}
});
but how in principle, I would add a fourth item key:value, how can I update or edit or change a value by key (say key:4) how can I remove by referencing the key, and how can I reference an elements value by the key without looping?
thanks in advance
First of all, that’s an object – not an array. Arrays can only have numerical indices and have special semantics such as a
.lengthproperty. Now, to answer your question.What you have there is a plain old JavaScript object, and you’re assigning properties on it. MDN has a complete page about them. Here’s a summary:
Accessing properties
Use the
o.keyoro["key"]syntax, for example:The
o["key"]syntax is particularly handy when using the object as a lookup table, for example:Setting properties
Similar to accessing properties, but now you place them on the left hand side of the assignment. It doesn’t really matter whether the property already exists or not, it will be created if necessary.
Deleting properties
Use the
deletestatement.