[英]How would I keep all items inside an array function? Javascript
How would I put all the numbers inputted in the function getNum()
, into the finalArr
Array
, without moving var finalArr = [];
我如何将在函数
getNum()
输入的所有数字放入finalArr
Array
,而无需移动var finalArr = [];
outside the function it is in? 它在功能之外? At the moment, no matter how many cycles I run the script, it only displays the very last number I entered.
此刻,无论我运行脚本有多少个周期,它只会显示我输入的最后一个数字。
function getNum () {
do {
number = Number(prompt("Enter a number:"));
}
while (number < 0);
return number;
}
function finalArray () {
var finalArr = [];
finalArr.unshift(number);
alert(finalArr);
return;
}
do {
getNum();
finalArray();
var no = prompt("Enter n to stop");
}
while (no != "n");
您必须在getNum()方法中调用finalArry()方法,并将其从do循环中删除。
Why don't you use a recursive function instead of a while loop? 为什么不使用递归函数而不是while循环?
Look at the next code: 看下面的代码:
var array = []; function getNum () { var no = prompt("Enter n to stop"); if (no === "n") { console.log("the final array is"); console.log(array); } else { array.push(no); getNum(); } } getNum();
EDIT: I don't understand why you want to declare the Array
inside the function, every variable declared inside a function lives just in that scope. 编辑:我不明白为什么要在函数内部声明
Array
,在函数内部声明的每个变量都位于该范围内。 But if it is necessary for you, you could pass the Array
value to the function, declare the Array
inside the function getting the value that you have passed and return the resulting Array
, it is a bit tricky but it works: 但是,如果您有必要,可以将
Array
值传递给函数,在函数内部声明Array
,以获取您传递的值,然后返回生成的Array
,这有点棘手,但是可以使用:
var array; function finalArray(array, number) { var finalArr = array || []; finalArr.push(number); return finalArr; } function getNum() { var no = prompt("Enter a number. Enter n to stop"); if (no === "n") { console.log("the final array is"); console.log(array); } else { array = finalArray(array, +no); getNum(); } } getNum();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.