I'm creating a playlist system where each song has a unique ID. When you add a song to the playlist array, its index is registered as its ID.
Normally when looping over a javascript开发者_JAVA百科 array, you grab the length and count up through the index. Is there a way to loop through an array with unused indexes? Is that bad practice for any reason?
var obj = {"123": "Lalala",
"456": "dum dum"};
for(var i in obj){
//i = ID
// obj[i] = "song"
}
Use for(var i in obj)
to loop through an object. See the comments above to understand the meaning of this for
-statement.
You're talking about Objects, not arrays, by the way:
var array = [7, 5, 9];
An array can be simulated in this way, so that a for(var i=0; i<array_like.length; i++)
can be used. Array functions (such as pop
) cannot be used on them, unless you define it:
var array_like = {0:7, 1:5, 2:9, length:3};
You can access the object's properties one of two ways. Either using a "." such as:
var my prop = obj.property;
Or via bracket notation:
var my prop = obj["property"];
Now, that doesn't really answer your question. So, here are a few ways:
Utilize jQuery's each function:
$.each(obj, function(key, value){
//Do something with your key and value.
});
Utilize the Javascript for function:
for(var key in obj)
{
var value = obj[key];
//Do something with your key and value.
}
Hope that helps!
You can also do just for each
to iterate over properties values only:
var obj = {"key1": "val1",
"key2": "val2"};
for each(var value in obj) {
....
}
But in this case, you are not able to access a property name.
Assuming your array is in the form:
array['id1'] = 'val1';
array['id2'] = 'val2';
array['id3'] = 'val3';
You can iterate over the values by using:
for (var id in array) {
document.write(id + ' – ' + array[id]);
}
精彩评论