Home > Blockchain >  Finding the first positive number in the array
Finding the first positive number in the array

Time:10-17

I want to show the first positive number in the array in the console blog, but according to my code, it displays the second one, which is 6. Please provide an answer to my problem and give an explain of how my code works.

let values = [-1, 5, -6, 6, -10, -5, 3, 4, -1, 8, 1, -10, 3];
  for (const number of values) {
            if (values[number] >= 0) {
                console.log(number); break;
            }
        } //6

        for (const key in values) {
            if (values[key] >= 0) {
                console.log(key);

            }
        } //6`enter code here`

CodePudding user response:

Since you are using of it will return the element value,so you need to use number >= 0 instead of values[number] >= 0

Or you can use in to do it,in this case,you need to use values[number] >= 0 rather than number >= 0

let values = [-1, 5, -6, 6, -10, -5, 3, 4, -1, 8, 1, -10, 3];
       for (const number of values) {
            if (number >= 0) {
                console.log(number); break;
            }
        } //5
        
       for (const number in values) {
            if (values[number] >= 0) {
                console.log(values[number]); break;
            }
        } //5
        
        console.log("----------------------------")
        for (const key in values) {
            if (values[key] >= 0) {
                console.log(key);

            }
        } //6`enter code here`

CodePudding user response:

You can iterate it with for loop with an index

let values = [-1, 5, -6, 6, -10, -5, 3, 4, -1, 8, 1, -10, 3];
  for (var i = 0; i<values.length; i  ) {
            if (values[i] >= 0) {
                console.log(values[i]); break;
            }
        } //6

  • Related