猿问

如何在循环 JavaScript 中跳过一个数字?

var text = "";

var i;

for (i = 0; i < 10; i++) {

  if (!i == 5)

  text += "The number is " + i + "<br>";


document.getElementById("demo").innerHTML = text;

<p id="demo"></p>


在上面的代码中,我想从 0 循环到 10,但我想跳过数字 5。我想从 0 显示到 4,跳过 5,然后从 6 显示到 10。上面的代码不起作用。


潇潇雨雨
浏览 132回答 3
3回答

ABOUTYOU

您可以使用continuevar text = "";var i;for (i = 0; i < 10; i++) {&nbsp; if (i == 5) continue;&nbsp; text += "The number is " + i + "<br>";}&nbsp;document.getElementById("demo").innerHTML = text;<p id="demo"></p>另一种方法是将代码包装在块内的if语句中forvar text = "";var i;for (i = 0; i < 10; i++) {&nbsp; if (i !== 5){&nbsp; &nbsp; text += "The number is " + i + "<br>";&nbsp; }}&nbsp;document.getElementById("demo").innerHTML = text;<p id="demo"></p>

翻过高山走不出你

if (!i == 5)应该if (i !== 5)

慕后森

您还可以创建一个生成器,生成不在其“跳过”列表中的索引。const rangeWithSkip = function*(start, end, skips) {&nbsp; for (let i = start; i < end; i++) {&nbsp; &nbsp; if (skips.includes(i)) continue;&nbsp; &nbsp; yield i;&nbsp; }}let textArr = [];for (let i of rangeWithSkip(0, 10, [3, 5, 8])) {&nbsp; textArr.push(`The number is ${i}`);}document.getElementById("demo").innerHTML = textArr.join('<br />');<p id="demo"></p>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答