Javascript for..in looping over arguments ie.for( arg in arguments) does not work in IE8 but it works in Chrome 8

前端 未结 6 1500
刺人心
刺人心 2020-12-31 17:01

I faced this strange situation where foreach like construct of javascript does not work in IE but it works in FF. Well not all for..in just this special funcito

6条回答
  •  情话喂你
    2020-12-31 17:41

    Some browsers support for..in like Chrome and Firefox 4 to iterate arguments, but other browsers don't see it's parameters while iterating like that. I bet that on these browsers if you did JSON.stringify(arguments) the result would be an empty object. By the specification of JavaScript 1.1 and further arguments have a length parameter, so that means you can iterate them using for (var i = 0; i < arguments.length; i++) and while(i < arguments.length) loops.

    Personally once I got burned using for..in for argument iteration I wrote a simple function for argument object iteration that doesn't depend on length, because the arguments are always labeled in order by IDs.

    var eachArg = function(args, fn, start_from, end_where) {
        var i = start_from || 0;
        while (args.hasOwnProperty(i)) {
            if (end_where !== undefined && i === end_where)
                return i;
            if (fn !== undefined)
                fn(i, args[i]);
            i++;
        }
        return i;
    };
    

    I use it ever since when I iterate arguments and it doesn't fail me. More on about it on my blog post http://stamat.wordpress.com/iterating-arguments-in-javascript/

提交回复
热议问题