Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get loop value outside the loop

How to get the loop values outside the loop below example only prints the last value, For example if i wanted to print the loop results.

var result;

    for (var i=0; i < 10; i++) {
          result = i;
    }

    console.log(result);

Now how can i get the iterated values of the loop which are (1 to 10) in the console, because now i will only print the last value which is 10.

like image 906
Osama Xäwãñz Avatar asked Oct 17 '25 22:10

Osama Xäwãñz


1 Answers

Put the log statement inside the loop where you set the value.

var result;

for (var i=0; i < 10; i++) {
    result = i;
    console.log(result);
}

If you only want one output statement, you can concatenate your results before logging:

var result = "";

for (var i=0; i < 10; i++) {
    result += i + " ";
}

console.log(result);

This will output 0 1 2 3 4 5 6 7 8 9 10

like image 188
Forklift Avatar answered Oct 20 '25 12:10

Forklift



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!