当运行条件设置为options.length时,为什么我的JavaScript for循环会提前停止?

sta*_*per 1 javascript loops

我构建了一个JavaScript for循环,其运行条件设置为选项Collection的长度.选项Collection的长度在循环之前通过console.log在27处验证.

但是当我运行循环时,它似乎只运行了14次 - 循环在每次迭代时删除一个选项,当它完成时,剩下13个选项.我也在循环后运行console.log.

这是一个JSFiddle.

这是我的for循环:

(function () {
    var industryOptions = document.getElementsByName("industry")[0].options;

    console.log(industryOptions.length);

    for (var k = 0; k < industryOptions.length; k++) {
        industryOptions.remove(0);
    }

    console.log(industryOptions.length);
})();
Run Code Online (Sandbox Code Playgroud)

注意:当我将条件从industryOptions.length27 更改为27时,它按预期工作.

为什么我的for循环在14个循环之后提前停止而不是整个industryOptions.length?谢谢!

dsh*_*dsh 6

industryOptions.remove(0);
Run Code Online (Sandbox Code Playgroud)

即使您要添加数字,也要不断更改数组的长度.您需要使用不同的算法或技术.

一种方法是简单地重复直到数组为空:

while (industryOptions.length > 0)
    { industryOptions.remove(0); }
Run Code Online (Sandbox Code Playgroud)

你可以从最后倒数而不是数数:

for (var k = industryOptions.length; k > 0 ; k -= 1)
    { industryOptions.remove(0); }
Run Code Online (Sandbox Code Playgroud)

另一种技术是在循环开始之前确定长度,而不是在每次迭代时重新评估长度:

var loopStop = industryOptions.length;
for (var k = 0; k < loopStop; k += 1)
    { industryOptions.remove(0); }
Run Code Online (Sandbox Code Playgroud)

或者你可以避免自己做这项工作并让数组处理它:

industryOptions.splice(0, industryOptions.length);
Run Code Online (Sandbox Code Playgroud)

另请参阅2009年的现有答案:如何在JavaScript中清空数组?