为什么扩频运算符将我的数组变成数字

问题描述 投票:0回答:2

我有

a = [[1,2,3],[4,5,6]]

我怎么写

console.log(...a.shift())它给了我1 2 3但不是1,2,3也不是[1, 2, 3]谁能解释一下这背后的机制?

javascript arrays operators arr spread
2个回答
0
投票

a.shift()返回数组的第一个元素,即[1, 2, 3]。因此,您的代码等效于:

console.log(...[1, 2, 3])

spread语法使数组的每个元素成为一个单独的参数,因此等效于

console.log(1, 2, 3)

将在控制台上分别打印每个数字。

要获取[1, 2, 3],您不应该使用...,只需写

console.log(a.shift())

获得1,2,3使用

console.log(a.shift().join(','))

0
投票

console.log(...a.shift())

以给定的顺序运行:

  1. a.shift()返回[1, 2, 3] => console.log(...[1, 2, 3])
  2. [...[1, 2, 3]被评估为1 2 3,并作为3个不同的参数传递给console.log => console.log(1, 2, 3)

哪个不在1 2 3

© www.soinside.com 2019 - 2024. All rights reserved.