我想知道如何联系不变的数组。想象一下我从数组list = [4,1]
开始,然后从So items = [5,2,6]
等动作响应中收到数组。我如何解决结果是 [4,1,5,2,6]
且该操作不可突变。
奖励:如何以相同的ID(不变的方式)覆盖项目?让我们想象一下我们在商店books=[{'id':1, 'title': 'Cool story'}, {'id':2, 'title': 'Bad story'}]
中的数组。其他需要覆盖书籍的数组(API的最后同步)otherArray = [{'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]
。因此,结果应该是[{'id':2, 'title': 'Bad story'}], {'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]
带有 es6 您可以使用破坏性:
const array1 = ["Banana","Apple"];
const array2 = ["Pineapple", "Peach"];
const array3 = [...array1, ...array2];
JavaScript没有不变的类型。
听起来您实际上是在要求连接阵列而不突变现有实例。
在文档中清楚地说明,concat()
方法可以做到。
尽管如前所述,内置方法.concat()
将解决您的问题,但您可能希望查看Lodash库。特别是,可以使用_.unionBy(otherArray, books, "id")
解决奖励问题。