【问题标题】:Create an array with values from other array with push without creating a bidimensional array (JavaScript) [duplicate]使用推送创建具有来自其他数组的值的数组而不创建二维数组(JavaScript)[重复]
【发布时间】:2020-02-10 05:19:55
【问题描述】:

我想创建一个值从 1 到 13 的数组,四次。这个最终数组应该有 52 个位置,并且是这样的:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10、11、12、13]

我已经创建了一个从 1 到 13 的数组

let suit = Array.from(new Array(13), (x, index) => index + 1)

并且想要将这个“花色”数组上的四倍值推入一个名为“deck”的最终数组。

为此,我尝试了以下代码:

let suit = Array.from(new Array(13), (x, index) => index + 1)
let suitsNumber = 4
let deck = []

for(let i = 0; i < suitsNumber; i++ ) {
   deck.push(suit)
}

问题是生成的数组“deck”是一个长度为 4 的二维数组,每个位置都是数组套装:

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, 11, 12, 13],[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [1, 2, 3, 4, 5, 6 , 7, 8, 9, 10, 11, 12, 13]]

有人能告诉我为什么没有按预期工作吗?

【问题讨论】:

  • deck.push(...suit) 代替。

标签: javascript arrays


【解决方案1】:

您可以只使用 concat 和扩展语法 ... 一个包含其他 4 个子数组的主数组。

const result = [].concat(...Array(4).fill(Array.from(Array(13), (_, i) => i + 1)))
console.log(result)

或者您可以在包含其他 4 个子数组的数组上使用flat() 方法。

const result = Array(4).fill(Array.from(Array(13), (_, i) => i + 1)).flat()
console.log(result)

【讨论】:

    【解决方案2】:

    你也可以这样做

    const suit = Array.from(new Array(13), (x, index) => index + 1)
    const deck = Array.from(new Array(suit.length * 4), (_, index) => suit[index % 13])
    

    【讨论】:

      【解决方案3】:

      您可以创建一个二维数组,并使用Array.flat() 将其展平:

      const suit = Array.from(new Array(13), (x, index) => index + 1)
      const suitsNumber = 4
      const deck = Array.from(new Array(suitsNumber), () => suit).flat()
      
      console.log(deck)

      或者使用Array.flatMap()创建数组:

      const suit = Array.from(new Array(13), (x, index) => index + 1)
      const suitsNumber = 4
      const deck = new Array(suitsNumber).fill(null).flatMap(() => suit)
      
      console.log(deck)

      【讨论】:

        【解决方案4】:

        使用deck.push(...suit) 代替deck.push(suit)。这会将单个数字推送到 deck 数组,而不是将整个 suit 数组推送到 deck 数组的索引。

        let suit = Array.from(new Array(13), (x, index) => index + 1)
        let suitsNumber = 4
        let deck = []
        
        for (let i = 0; i < suitsNumber; i++) {
          deck.push(...suit)
        }
        
        console.log(deck)

        【讨论】:

          猜你喜欢
          • 2021-04-28
          • 1970-01-01
          • 2021-08-01
          • 1970-01-01
          • 2016-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多