I want to make the sequence stop when the last value stored in the array is bigger than 1000.
I have the js code for the sequence and i can make it stop at whatever position i want with the variable limit. But i dont know how to make it stop at a certain number.
The is my code:
JavaScript
x
18
18
1
let fib = [1,1];
2
let limit = 20;
3
4
function fibonacci(nums) {
5
let data = [1,1];
6
7
for(let i = 2; i < limit; i++) {
8
nums[i] = nums[i - 1] + nums[i - 2];
9
data.push(nums[i]);
10
}
11
12
return data;
13
14
15
}
16
17
console.log(fibonacci(fib))
18
Advertisement
Answer
You can just use an if condition and break out of the loop as soon as a value is bigger than 1000. In this example I pushed the value and then break out of the loop. You can also break before pushing it to the array
JavaScript
1
19
19
1
let fib = [1, 1];
2
let limit = 20;
3
4
function fibonacci(nums, breakLimit) {
5
let data = [1, 1];
6
7
for (let i = 2; i < limit; i++) {
8
nums[i] = nums[i - 1] + nums[i - 2];
9
if (nums[i] > breakLimit) {
10
data.push(nums[i]);
11
break;
12
} else {
13
data.push(nums[i]);
14
}
15
}
16
return data;
17
}
18
19
console.log(fibonacci(fib, 1000))