Tell me, please, how to create a one-dimensional array in js , of n elements, filled with numbers of the Fibonacci sequence, and display.
- 3Create, fill, display. What exactly is the question? - Vladimir Martyanov
- 3Possible duplicate question: How to fix this js function? - Darth
- @Darth, I would not say that it is a duplicate. The link is required to generate a Fibonacci sequence with certain restrictions imposed on the code. - Dmitriy Simushev
- Is it difficult to add var array = [] and array.push (the next number)? - Darth
- @Darth, not difficult, it's just not quite a duplicate :) Although this is just my subjective opinion. - Dmitriy Simushev
4 answers
var n = 10; // Сколько элементов хотим получить var fibonacci = [0, 1]; // Первые два элемента последовательности Фибоначчи for (i = 2; i < n; i ++) { // Получаем i-й элемент последовательности как сумму предыдущих двух fibonacci[i] = fibonacci[i-1] + fibonacci[i-2]; } console.log(fibonacci.slice(0,n)); // slice отрезает от массива первые n элементов, если n < 2 - And how is your answer fundamentally different from the answer @ A1essandro? - Dmitriy Simushev
- oneYour solution will not work for
n = 1- Dmitriy Simushev - Thanks, corrected the decision! - installero
Set n , which must be greater than or equal to 0, then:
var f = [0, 1]; //Первые значения if (n <= 2) { //если n <= 2 var result = f.slice(0, n); //записываем в результат срез f от 0 до n } else { for (i = 0; i < n - 2; i++) { // повторяем n-2 раза, т.к. 2 элемента уже есть f.push(f[f.length - 1] + f[f.length - 2]); //заполняем (n+2)-й элемент } var result = f; //записываем в result наш массив f } alert(result); //вывод result на экран (через алерт) f[f.length - 1] gets the last element of the array, f[f.length - 2] - the penultimate.
Array.Push () - the method of inserting the element at the end of the array.
Array.Slice () - method returning array slice
Here infa generally about arrays.
- Why do not you love so much
;,{and}?) - Dmitriy Simushev - I apologize for some time kodil on Python'e)) - A1essandro
Wrap all the code in the f-yu:
function fibi(n) { // число n передадим параметром в ф-ю Initialize the variable that will contain the current value of the sum:
var sum = 0 iteration counter:
,i text string for array output:
,str and the array itself:
,arr = [] ; Twist the loop, where we will count the iterations to reach n:
for( i=0; i<n; i++) { The next value of the array is obtained by adding to the “current” sum (later we insert it at the end of the array) of the last but one element of the array. There are two special cases: when the array is empty, we insert 0; and when there is only one element in it, then we add one to the tail.
if( arr.length > 1) sum += arr[ arr.length-2]; if( arr.length == 1) sum = 1; if( arr.length == 0) sum = 0; We push this value into the end of the array:
arr.push( sum); End of the cycle - repeat, but do not shake:
} Get the array as a string for output:
str = arr.join(", "); // склеить элементы массива запятой-с-пробелом Print to console:
console.log(str); Or in the document, since there is a "web programming" tag:
document.body.innerHTML = str; End of code and f-s:
} Checking :
fibi(4); // выводит 0, 1, 1, 2 If it is completely lazy, then you can solve it like this:
var fibonacci = new Array(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946); alert(fibonacci); but in general google "javascript arrays" - everything is elementary there.
- Although in general, your answer is not true, but still I ply for the laziness :) - Dmitriy Simushev
- Thank you, but we are not specified, the number n. - Yuriy Zatochniy