2

Something like this works, but looks a bit clumsy:

for (i in {foo: 1, bar: 1, wah: 1}) {  // loops through foo, bar, wah
  console.log(i + " haha");            // can view using Firebug or Chrome 
}

if using an array, I don't want to create any global temporary variable for the array... Also, this has to work in any modern browser IE7 / FF / Chrome / Safari. thanks.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

7 Answers7

3

You need to declare i for certain browsers.

I would use the initialization section of a for loop to declare the variables.

Array:

for (var i = 0, arr = ['foo', 'bar', 'wah']; i < arr.length; i++) {
  console.log(arr[i] + " haha");
}
Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
  • `i` is not a name that needs to be declared. It can be *any* variable name. It should just be prefixed with `var`, so that it is not added to the global scope. `i` is just very common. – BastiBen Nov 29 '10 at 20:41
  • @badcat - declared as in var i;. In internet explorer it will not add the variable to the window namespace. Rather throw an exception that i is undeclared. – Josiah Ruddell Nov 29 '10 at 20:48
2

If the requirement is that you don't want to create a variable in the global (or current) scope, but just want to use the Array literal, then use forEach, though you'll need to prototype it into browsers that don't support it.

["foo", "bar", "wah"].forEach(function( v, i, arr ){
  console.log(i + ' ' + v + " haha");
});

Here's MDC's implementation of a forEach to prototype into Array.

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
        fun.call(thisp, t[i], i, t);
    }
  };
}
user113716
  • 318,772
  • 63
  • 451
  • 440
1

Okay I'm posting this cause I like strange code, so go easy on me...

If you absolutely do not want to create a temporary variable, global or local, and cannot use or add the forEach function (as in patrick dw's answer), you can drag out the dreaded with statement to do the job. It's not exactly pretty...

with(['foo', 'bar', 'wah'])
  while(valueOf().length)
    console.log(valueOf().shift())

Look ma, no variables!

If you are okay with using lexically scoped variables, then you can do things a bit cleaner...

with({a: ['foo', 'bar', 'wah']})
  while(a.length)
    console.log(a.shift())

You could do the same thing with a self-executing anonymous function, but with horrid syntax and (likely) lesser performance.

Regardless, I strongly recommend you use forEach if you can, or just...you know, local variables.

MooGoo
  • 46,796
  • 4
  • 39
  • 32
0

I think that will look better:

   function show(arr){
     for(el in arr){
      console.log(arr[el])   
     }    
    }
    show({foo: 1, bar: 1, wah: 1});
Eldar Djafarov
  • 23,327
  • 2
  • 33
  • 27
0

Why not use the var keyword to denote a local variable (as variables declared without the var keyword are automatically global).

Also { ... } denotes a JavaScript object, not an array. You can define arrays with [ ... ]:

var myArray = ["one", "two", "three"];

for (var i in myArray) {
    console.log(myArray[i] + " haha");
}

Hope that helps!

BastiBen
  • 19,679
  • 11
  • 56
  • 86
  • @badcat: Umm... I don't think that your second example works. – thejh Nov 29 '10 at 20:31
  • @thejh, you are right. I just realized that, too. ;) Maybe I need more coffee. Removed second example. – BastiBen Nov 29 '10 at 20:32
  • That is fine. You could probably make it more compact, but at this technique always gave me best readability and comfort, especially when that said array is needed in more places than the loop. – BastiBen Nov 29 '10 at 20:40
  • 1
    @badcat: First example also doesn't work, it also fetches properties of the array and so on. – thejh Nov 29 '10 at 20:40
  • @badcat: works with pure JS, but not with, for example, mootools: http://jsfiddle.net/NhfsY/ – thejh Nov 29 '10 at 20:42
  • The `for-in` statement is not really recommended to be used with array or array-like objects, is [slow](http://vocamus.net/dave/?p=1205) and you can get unexpected problems [more info...](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays/4261096#4261096) – Christian C. Salvadó Nov 29 '10 at 21:10
  • lets just say it is completely unrelated to arrays and works only because of JS's looseness – Free Consulting Nov 29 '10 at 21:24
0

You want to be careful when using for in as you may get keys that are in the prototype chain and not actually part of the object. So in your example you'd want to use:

var obj = {foo: 1, bar: 1, baz: 1};
for(var key in obj) {
   if(obj.hasOwnProperty(key)) {
       console.log(key, obj[key]); //key, value
   }
}
illvm
  • 1,336
  • 13
  • 28
0

How about

javascript:
Array.prototype.enum = function (fn) {
  for( var i=0; i < this.length; i++ )
    fn( this[i] )
};

["one","two","tri"].enum( function(item){
  alert(item)
})

reformatted

Free Consulting
  • 4,300
  • 1
  • 29
  • 50