What does [literal] in [array/object] mean?

后端 未结 5 581
忘掉有多难
忘掉有多难 2021-01-23 12:20

What does the following syntax mean:

1 in [1,2,3,5]

I know it doesn\'t search for 1 in the array. But what does it do?

I\'ve seen it u

5条回答
  •  闹比i
    闹比i (楼主)
    2021-01-23 13:20

    It's used to iterate JavaScript objects.

    This loop will iterate through each "key" in the object.

    Its common usage is iterate through such objects:

    var Car = { color: "blue", price: 20000 };
    for (var key in Car)
        console.log("Propery " + key + " of Car is: " + Car[key]);
    

    Live test case - check Chrome/Firefox JavaScript console to see the output.

    When used for plain arrays, each "key" will be the index.. for example:

    var nums = [20, 15, 30]
    for (var key in nums)
        console.log("Propery " + key + " of array is: " + nums[key]);
    

    Will show the keys as 0, 1 and 2. Updated fiddle for such case.

提交回复
热议问题