JavaScript for…in vs for

前端 未结 22 1192
悲哀的现实
悲哀的现实 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条回答
  •  -上瘾入骨i
    2020-11-22 07:18

    Although they both are very much alike there is a minor difference :

    var array = ["a", "b", "c"];
    array["abc"] = 123;
    console.log("Standard for loop:");
    for (var index = 0; index < array.length; index++)
    {
      console.log(" array[" + index + "] = " + array[index]); //Standard for loop
    }
    

    in this case the output is :

    STANDARD FOR LOOP:

    ARRAY[0] = A

    ARRAY[1] = B

    ARRAY[2] = C

    console.log("For-in loop:");
    for (var key in array)
    {
      console.log(" array[" + key + "] = " + array[key]); //For-in loop output
    }
    

    while in this case the output is:

    FOR-IN LOOP:

    ARRAY[1] = B

    ARRAY[2] = C

    ARRAY[10] = D

    ARRAY[ABC] = 123

提交回复
热议问题