【问题标题】:Javascript Array concat functionJavascript数组连接函数
【发布时间】:2019-11-15 12:52:21
【问题描述】:

案例1

let history = [{temp : 123}];
history.concat({temp:1234}); //[{temp :123}, {temp:1234}]

案例2

let history = [{temp : 123}];
history.concat([{temp:1234}]): //[{temp :123}, {temp:1234}]

案例3

let history = [{temp : 123}];
history.concat([[{temp:1234}]]); //[{temp :123}, [{temp:1234}]]

为什么 concat 方法在 case1 和 case2 中返回相同的输出?

根据我的情况,case1 和 case3 是预期的,但 case2 是意外的。

【问题讨论】:

标签: javascript arrays concat


【解决方案1】:

case1:array.concat(nonArray) -> 将 nonArray 添加到数组中

case2: array.concat(newArray) -> 将 newArray 的每个元素添加到数组中

case3: array.concat(twoDArray) -> 将 twoDArray 的每个元素添加到数组中,但是 twoDArray 的每个元素都是一个数组。

case2 实际上与 case3 的行为完全相同

【讨论】:

  • 案例 1 的行为与案例 2 完全相同。edit 除非您的意思是执行相同的基本操作,这当然是正确的。使用来自 OP 的实际数据,结果在 1 和 2 之间是相同的。
  • 错了。案例 2 和案例 3 具有相同类型的参数,即数组。第一种情况是奇怪的,因为你传递的是一个对象而不是一个数组
  • 是的,但措辞令人困惑,因为它与 OP 中的内容相呼应,而结果正是 OP 所混淆的内容。
  • 我正在解释案例 2 和案例 3 中发生的情况,以及为什么他们做的事情完全相同。当您将数组传递给concat 时,它会添加该数组的每个元素。案例 3 添加了一个二维数组,因此您将数组添加到数组中,而不是对象。
  • 当然,我明白发生了什么,你当然是对的。
猜你喜欢
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
  • 2022-11-05
  • 2014-03-10
  • 1970-01-01
相关资源
最近更新 更多