while(i--)循环使用javascript

时间:2015-06-19 02:24:52

标签: javascript

我通常使用while循环:

while (i<some_value) 

我看到了 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**

但是当我尝试......

while((num_arr.length)--) console.log(num_arr);
[4, 8, 7, 1]
[4, 8, 7]
[4, 8]
[4]
[] // WHY IS THIS HAPPENING??

使用此语法需要了解一些隐藏的内容吗?

3 个答案:

答案 0 :(得分:8)

数组'animatorSet属性是可写的,并且在设置时会截断它们的元素或添加空插槽。

length

所以,不要这样做。

答案 1 :(得分:2)

执行array.length--时,您可能每次将数组缩短一个元素

请参阅缩短数组部分中的参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

Array.prototype.length可以通过编程方式重新编写,并且可能会按照您指定的新长度缩短数组。

例如

a = [1,2,3,4,5,6,7,8,9,10];

// Shorten the array by one element
a.length--; // a <-- [1,2,3,4,5,6,7,8,9]

// In case you want to shorten your array to 3 elements, you can:
a.length = 3; // a <-- [1,2,3]

答案 2 :(得分:1)

当您将数组的length属性设置为较低值时,最后的项目将被删除:

var arr = [1,2,3,4,5];
arr.length; // 5
arr.length = 3;
arr; // [1,2,3]

spec

中对此进行了描述
  

newLen &lt; oldLen 重复,

     
      
  1. oldLen 设为 oldLen - 1。
  2.   
  3. deleteSucceeded 成为调用 A 传递ToString oldLen )的[[Delete]]内部方法的结果和错误   作为参数。
  4.   

在您的代码中,您使用postfix decrement operator--)来减少数组的length