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 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With