【问题标题】:Why can't I concatenate these two arrays? [duplicate]为什么我不能连接这两个数组? [复制]
【发布时间】:2016-12-08 08:08:19
【问题描述】:

这是代码(Vuex 突变):

export const CREATE_PANORAMAS = (state, panoramas) => {
  console.log('building.panoramas:', state.building.panoramas)
  console.log('panoramas:', panoramas)
  state.building.panoramas.concat(panoramas)
  console.log('result:', state.building.panoramas)
} 

这是相应日志的结果:

[] // building.panoramas
[{ name: "", objectId: "5849133aac502e006c581b58" }] // panoramas
[] // result

为什么两个数组不连接?

【问题讨论】:

  • console.building.panoramas.concat 这对我来说很奇怪,但我不是这方面的专家
  • @AlexSzabó 这是一个错字。它不在实际代码中。
  • 你试过Array.prototype.push.apply(state.building.panoramas, panoramas)吗?
  • Array#concat不可变的

标签: javascript vue.js vuex


【解决方案1】:

来自documentation - concat() 方法用于合并两个或多个数组。 此方法不会改变现有数组,而是返回一个新数组。

使用 concat 的一种方法是执行以下操作

state.building.panoramas = state.building.panoramas.concat(panoramas)

或者你可以简单地

[].push.apply(state.building.panoramas, panoramas);

【讨论】:

    【解决方案2】:

    问题是您没有将连接的结果分配给@JaromandaX 所指示的state.building.panoramas 数组。

    还可以使用rest元素、spread元素、解构赋值来连接两个或多个数组

    [...state.building.panoramas] = [...state.building.panoramas, ...panoramas];
    

    【讨论】:

      【解决方案3】:

      我认为您需要先将 state.building.panoramas.concat(panoramas) 分配给某些东西,或者您可以直接将其放在“结果”行

      sampleArray.concat(moreValues) 返回连接数组,它不会连接 'moreValues' 到 sampleArray 本身。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-22
        • 2021-12-11
        • 2019-12-24
        • 1970-01-01
        • 2021-07-05
        • 2020-07-16
        • 1970-01-01
        相关资源
        最近更新 更多