我试图获取allArrays变量以包含已定义的数组,然后使用该函数在console.log中打印它们。当我尝试这个时,我得到3个具有未定义值的数组,为什么会这样,这将如何工作?
var allArrays = [food, drinks, random];
var food = ["burger","fries","milkshake","sushi"];
var drinks= ["cola","soda","pop"];
var random = ["suck","give","fix me","wooww"];
function selectallArrays (allArrays){
for (var i =0; i<allArrays.length; i++) {
console.log(allArrays);
}
console.log("--------");
}
selectallArrays(allArrays);
答案 0 :(得分:0)
您可以更改声明的顺序&amp;初始化数组,否则将记录undefined
。
所有数组都使用var语句声明,并且不会被提升。
执行var allArrays = [food, drinks, random];
时food
,drinks
&amp; random
数组未初始化。
var food = ["burger","fries","milkshake","sushi"];
var drinks= ["cola","soda","pop"];
var random = ["suck","give","fix me","wooww"];
var allArrays = [food, drinks, random];
答案 1 :(得分:0)
现在应该可以了。
var food = ["burger","fries","milkshake","sushi"];
var drinks= ["cola","soda","pop"];
var random = ["suck","give","fix me","wooww"];
var allArrays = [food, drinks, random];
function selectallArrays (allArrays){
for (var i =0; i<allArrays.length; i++) {
console.log(allArrays);
}
console.log("--------");
}
selectallArrays(allArrays);
答案 2 :(得分:0)
这是因为您在定义allArrays
,food
等其他数组的值之前已在顶部定义了drinks
,
在定义其他数组后定义allArrays
,
试试这个
var food = ["burger","fries","milkshake","sushi"];
var drinks= ["cola","soda","pop"];
var random = ["suck","give","fix me","wooww"];
var allArrays = [food, drinks, random];
function selectallArrays (allArrays){
for (var i =0; i<allArrays.length; i++) {
console.log(allArrays[i]);
}
console.log("--------");
}
selectallArrays(allArrays);