我通常使用while循环:
while (i<some_value)
Run Code Online (Sandbox Code Playgroud)
我看到while(i--)语法并且认为它更短更凉爽并且在google-chrome中尝试了以下内容.
var num_arr= [4,8,7,1,3];
var length_of_num_arr=num_arr.length;
while(length_of_num_arr--) console.log(num_arr);
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3] **// THIS IS EXPECTED RESULT**
Run Code Online (Sandbox Code Playgroud)
但是当我尝试......
while((num_arr.length)--) console.log(num_arr);
[4, 8, 7, 1]
[4, 8, 7]
[4, 8]
[4]
[] // WHY IS THIS HAPPENING??
Run Code Online (Sandbox Code Playgroud)
使用此语法需要了解一些隐藏的内容吗?
数组的length属性是可写的,并且在设置时会切断它们的元素或添加空插槽.
var items = [1, 2, 3, 4, 5];
items.length = 3; // items is now [1, 2, 3]
items.length = 6; // items is now a sparse array: [1, 2, 3, undefined × 3]
Run Code Online (Sandbox Code Playgroud)
所以,不要这样做.