Reputation: 36299
Am I doing something wrong here? I have an array of tags, and when I do a jQuery each()
on the array it doesn't go into the each()
I did have an alert
in the each but nothing happens. I have checked my error log console and there are no errors. So, what am I doing wrong?
var tags = new Array();
tags["video-games"] = "Video Games";
tags["sports"] = "Sports";
tags["movies"] = "Movies";
tags["board-games"] = "Board Games";
tags["news"] = "News";
tags["television"] = "Television";
tags["computers"] = "Computers";
tags["opinions"] = "Opinions";
tags["reviews"] = "Reviews";
function updateTags(){
console.log(tags);
$("div.tags > div > span:first-child").nextAll().remove();
$.each(tags, function(key, val){
$("div.tags > div").append("<span><a class='tag' href='/tags/" + key + "'>" + val + "</a></span>");
});
}
updateTags();
Upvotes: 0
Views: 2793
Reputation: 22619
Your code is object and properties
var tags = {};
tags["video-games"] = "Video Games";
or
var tags = {
"video-games" : "Video Games";
};
Then
$.each(tags, function(key, val) {
$("div.tags > div").append("<span><a class='tag' href='/tags/" + key + "'>"
+ val + "</a></span>");
});
Upvotes: 0
Reputation: 1570
So in this case
var tags = {};
tags["video-games"] = "Video Games";
tags["sports"] = "Sports";
tags["movies"] = "Movies";
tags["board-games"] = "Board Games";
tags["news"] = "News";
tags["television"] = "Television";
tags["computers"] = "Computers";
tags["opinions"] = "Opinions";
tags["reviews"] = "Reviews";
function updateTags(){
//console.log(tags);
$("div.tags > div > span:first-child").nextAll().remove();
for(var key in tags){
$("div.tags > div").append("<span><a class='tag' href='/tags/" + key + "'>" + tags[key] + "</a></span>");
}
}
updateTags();
Should work.
Upvotes: 0
Reputation: 887305
Arrays are expected to have numeric indexes.
You've created an empty array which happens to have some properties.
You should create an ordinary object instead:
var tags = {
"video-games": "Video Games",
...
};
Upvotes: 10