Just_some_Noob
Just_some_Noob

Reputation: 139

Trying to log an array in a loop, and return a string if array index is equal to a certain variable

I have a simple array that I want to run in a loop. While I want to log each value of the array to the console, I also want to log a string only IF the index of the array matches the value of a variable..

Here is what I got.

let myVal = 10;
let digit = [12,4,11,10]

for (let i = 0; i < digit.length; i++) {
  console.log(digit[i]);
  if (myVal == digit[3]) {
    console.log(digit[3] && ' Hooray!');
  }
}

What I am seeing is the console is logging both, so I get this:

12
Check!
4
Check!
11
Check!
10
Check!

I am looking for something like this:

12
4
11
10 Check!

Upvotes: 0

Views: 117

Answers (4)

Echtniet
Echtniet

Reputation: 188

You need to evaluate against the current index.

I would suggest something like this

let myVal = 10;
let digit = [12, 4, 11, 10]
for (let i = 0; i < digit.length; i++){
    if (digit[i] == myVal)
        console.log(digit[i] + 'Hooray!');
    } else {
        console.log(digit[i]);
    }
}

Or just use a for in loop which looks like this:

for (x in digit) {
    if (digit[x] == myVal)
        console.log(digit[x] + 'Hooray!');
    } else {
        console.log(digit[x]);
    }
}

Also && is used for "and" in evaluations and + is used for concatenation of string.

Upvotes: 0

Gerardo BLANCO
Gerardo BLANCO

Reputation: 5648

Small error on your loop.

Always use your iterator when you have an if inside a loop

Hope it helps

let myVal = 10;
let digit = [12, 4, 11, 10]

for (let i = 0; i < digit.length; i++) {
  if (digit[i] == myVal)
    console.log(digit[3] + ' Check!');
  else
    console.log(digit[i]);
}

Upvotes: 0

GilBenDavid
GilBenDavid

Reputation: 35

You want check the indexes ?

for (let i = 0; i < digit.length; i++) {
    console.log(digit[i]);
    if (myVal == digit[i]) //check the index not digit[3] every loop
        console.log(digit[i] + ' Hooray!');   //print the index using string concatenation
}

im also noob :)

Upvotes: 3

thisisdamon
thisisdamon

Reputation: 71

Since you're in a loop, you won't need to check for digit[3], you can just check for digit[i].

let myVal = 10;
let digit = [12, 4, 11, 10];

for (let i = 0; i < digit.length; i++) {
    if (digit[i] == myVal){
        console.log(digit[i] + ' Hooray!');
    } else {
      console.log(digit[i]);
    }
}

I also added an else for printing the rest of the digits separately. Lastly, you'll want to use "+" instead of "&&" if you want to append text to your result.

Upvotes: 3

Related Questions