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`
Since you are using
ofit will return the element value,so you need to usenumber >= 0instead ofvalues[number] >= 0Or you can use
into do it,in this case,you need to usevalues[number] >= 0rather thannumber >= 0