JavaScript for…in vs for

前端 未结 22 1177
悲哀的现实
悲哀的现实 2020-11-22 07:15

Do you think there is a big difference in for...in and for loops? What kind of \"for\" do you prefer to use and why?

Let\'s say we have an array of associative array

22条回答
  •  逝去的感伤
    2020-11-22 07:20

    Be careful!!! I am using Chrome 22.0 in Mac OS and I am having problem with the for each syntax.

    I do not know if this is a browser issue, javascript issue or some error in the code, but it is VERY strange. Outside of the object it works perfectly.

    var MyTest = {
        a:string = "a",
        b:string = "b"
    };
    
    myfunction = function(dicts) {
        for (var dict in dicts) {
            alert(dict);
            alert(typeof dict); // print 'string' (incorrect)
        }
    
        for (var i = 0; i < dicts.length; i++) {
            alert(dicts[i]);
            alert(typeof dicts[i]); // print 'object' (correct, it must be {abc: "xyz"})
        }
    };
    
    MyObj = function() {
        this.aaa = function() {
            myfunction([MyTest]);
        };
    };
    new MyObj().aaa(); // This does not work
    
    myfunction([MyTest]); // This works
    

提交回复
热议问题