Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么在使用push()时总是在数组中获取数组?_Javascript_Arrays_Function_Ecmascript 6 - Fatal编程技术网

Javascript 为什么在使用push()时总是在数组中获取数组?

Javascript 为什么在使用push()时总是在数组中获取数组?,javascript,arrays,function,ecmascript-6,Javascript,Arrays,Function,Ecmascript 6,我试图理解MDN关于和的文档,因为我遇到了一个问题,即我最终在项目中的数组中找到了一个数组。我设置了一些实验代码来说明我的问题 有人能解释为什么foo()中的数组内容在另一个数组中打印吗?我不明白为什么它不为两个console.log()实例打印一个数组 var animals = []; var chickens = 'chickens'; var cows = 'cows'; animals.push(cows); animals.push(chickens); console.log(

我试图理解MDN关于和的文档,因为我遇到了一个问题,即我最终在项目中的数组中找到了一个数组。我设置了一些实验代码来说明我的问题

有人能解释为什么
foo()中的数组内容在另一个数组中打印吗?我不明白为什么它不为两个
console.log()
实例打印一个数组

var animals = [];
var chickens = 'chickens';
var cows = 'cows';

animals.push(cows);
animals.push(chickens);

console.log(animals); // > Array ["cows", "chickens"]

function foo(...animals) {
  console.log(animals); // > Array [["cows", "chickens"]] <-- why is this one inside another array?
}; 
因为
..
(rest/spread语法)用传递的参数生成一个新数组-所以用
[“鸡”,“牛”]
生成一个数组将导致
[[“鸡”,“牛”]
。通过删除
foo
中的
来解决此问题

var动物=[];
var鸡=‘鸡’;
var cows=‘cows’;
动物。推(牛);
动物。推(鸡);
控制台.日志(动物);
功能食品(动物){
控制台.日志(动物);
}; 
富(动物);

.as控制台包装{max height:100%!important;top:auto;}
阅读此
->

/“Rest参数”接收
//一个类似的数组对象,并使用其索引创建数组。
函数fn(…参数){
控制台日志(params);
} 
fn(“Ele”、“From”、“Stack”);//多个参数将作为数组的索引展开。
fn([“Ele”,“From”,“Stack”]);//在这种情况下,一个参数(数组)将用作数组中的唯一索引。
fn();//在这种情况下,将生成一个空数组。

。作为控制台包装{max height:100%!important;top:0;}
这就是
..
的作用。。与仅使用
参数
的方法相同,它将是一个数组,因此您传入一个参数,它将位于
动物[0]
中,这是您传入的值,传入2您的see 2元素。这就是
..
扩展/rest操作符所做的。还要检查详细信息,将函数参数命名为与全局变量相同可能会导致混淆。Yes@Derek,但是,它总是可以工作的,因为JavaScript在向外移动一层之前首先在当前范围中查找同名变量,因此函数中的局部变量优先于同名的全局变量。是的,简称为“变量阴影”。但无论如何,@Derek是对的,将参数命名为变量肯定会导致混淆。
animals.push.apply(animals, cows);
animals.push.apply(animals, chickens);

// Error: second argument to Function.prototype.apply must be an array