1

I have an array of div names (with no hash), and i'm using the following jQuery code do do something with them:

for(dayList in dayLists) {
  dayListID = "#" + dayList;
  $(dayListID).append("test");
}

Unfortunately, it does not work. I can see in the console that dayListID is an "HTMLDivElement", rather than the string that JQ is expecting. How can I join a hash and the div name while keeping the result as a string? Thanks!

JJJollyjim
  • 5,837
  • 19
  • 56
  • 78

3 Answers3

6

Don't use a for...in loop to iterate over arrays. Use a regular ol' for loop:

for(var i=0; i<dayLists.length; i++) {
  dayListID = "#" + dayLists[i];
  $(dayListID).append("test");
}

See for yourself what the difference is: http://jsfiddle.net/mattball/h9hpr/

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Thanks, done that. It still confuses me after having drilled into my head when learning PHP that "foring through arrays is evil, foreaching is good". – JJJollyjim Dec 11 '11 at 02:30
  • @JJ56 In JavaScript `for .. in` for arrays is like using a nuclear missile to hit a bird. It is slow and you might get a lot of unwanted side-effects. – kubetz Dec 11 '11 at 02:34
  • @JJ56 now it is time for this to get drilled into your head: ***JavaScript is not PHP.*** – Matt Ball Dec 11 '11 at 02:59
2

Try this:

for(dayList in dayLists) {
  dayListID = "#" + dayLists[dayList];
  $(dayListID).append("test");
}

dayList in for .. in is not a i-th value of the dayLists, but it is the index. So for array ["one", "two"] variable dayList is 0, 1 and to get the values you must use dayLists[dayList].

As Matt wrote in the comments it is good to use hasOwnProperty to make sure the properties we are looping through are the objects own.

for(dayList in dayLists) {
  if(dayLists.hasOwnProperty(dayList) {
    dayListID = "#" + dayLists[dayList];
    $(dayListID).append("test");
  }
}

... and then you realize the standard simple for loop (answer by MДΓΓ БДLL) is actually a better idea. The standard for is also faster.

See details HERE.

Community
  • 1
  • 1
kubetz
  • 8,485
  • 1
  • 22
  • 27
  • You should really use `hasOwnProperty` in that loop, as you'll iterate over a lot of other junk that you don't want/care about. – Matt Greer Dec 11 '11 at 02:18
  • 1
    Much better to just use [the right tool for the job](https://developer.mozilla.org/en/JavaScript/Reference/Statements/for). – Matt Ball Dec 11 '11 at 02:24
  • @MДΓΓБДLL Indeed. I was updating my answer to mention benefits of the simple `for` and link to troubles when you wrote that comment :). – kubetz Dec 11 '11 at 02:30
2

You should be using this:

dayLists = ["something", "somethingElse"];
for(var i=0; i<dayLists.length; i++){
    $("#" + dayList[i]).append("test");
}
vdbuilder
  • 12,254
  • 2
  • 25
  • 29