Elias Achilles
Elias Achilles

Reputation: 89

How to skip a number in loop 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>

In the code above I want to loop from 0 to 10 but i want to skip number 5. I want to show from 0 to 4, skip 5, then show from 6 to 10. The code above does not work.

Upvotes: 0

Views: 1162

Answers (4)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

You could also create a generator that yields indices that are not in its "skips" list.

const rangeWithSkip = function*(start, end, skips) {
  for (let i = start; i < end; i++) {
    if (skips.includes(i)) continue;
    yield i;
  }
}

let textArr = [];
for (let i of rangeWithSkip(0, 10, [3, 5, 8])) {
  textArr.push(`The number is ${i}`);
}
document.getElementById("demo").innerHTML = textArr.join('<br />');
<p id="demo"></p>

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

If you add !(i == 5) then the solution will work.

var text = "";
var i;
for (i = 0; i < 10; i++) {
  if (!(i == 5))
  text += "The number is " + i + "<br>";
} 

document.getElementById("demo").innerHTML = text;
<div id="demo"></div>

Or either shorter way with ES6 which I prefer:

const reduce = (a, c, i) => i === 5 ? a : a.concat(`The number is ${c}<br>`);
const text = Array.from(Array(10).keys()).reduce(reduce, '');

document.getElementById("demo").innerHTML = text;
<div id="demo"></div>

I hope this helps!

Upvotes: 1

andy mccullough
andy mccullough

Reputation: 9561

if (!i == 5) should be if (i !== 5)

Upvotes: 2

Maheer Ali
Maheer Ali

Reputation: 36564

You can use continue

var text = "";
var i;
for (i = 0; i < 10; i++) {
  if (i == 5) continue;
  text += "The number is " + i + "<br>";
} 

document.getElementById("demo").innerHTML = text;
<p id="demo"></p>

Another way is to wrap the code inside an if statement inside for block

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>

Upvotes: 2

Related Questions