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

前端 未结 6 1480
刺人心
刺人心 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 18:01

    From my test, with Firefox 3.6.13 and IE 8 I don't see any difference in behavior, they both don't go in the second loop.

    One difference between mycars and arguments is that mycars is an Array, while arguments is an Object.

    To demonstrate this:

    alert(mycars.constructor);    //shows: "function Array() { [native code] }"
    alert(arguments.constructor); //shows: "function Object() { [native code] }"
    

    However, with some test code I can see that "for in" works for Array and Object

    var showWithForIn = function (myArgument) {
        for (i in myArgument) {
            alert(myArgument[i]);
        }
    };
    
    var testArray = function() {
        var mycars = new Array(); //some 
        mycars[0] = "Saab";
        mycars[1] = "Volvo";
        mycars[2] = "BMW";
        showWithForIn(mycars);
    };
    
    var testObject = function() {
        var myFriends = {
            0: 'John',
            1: 'Aileen'
        };
        showWithForIn(myFriends);
    };
    
    function testAll() {
        testArray();
        testObject();
    }
    

    So, I am not sure how the arguments Object is different from an Object you construct yourself with the curly braces literal. I think it is confusing, because in this test for in works for both the Array and the Object. While the "for in" doesn't work with arguments.

    Again, in all tests I didn't notice any difference between FF 3.6 and IE 8.

    UPDATE: As I discovered thanks to Ken comments, arguments properties are defined as not enumerable, while when defining an Object literal properties are implicitly defined as enumerable.

提交回复
热议问题