为了账号安全,请及时绑定邮箱和手机立即绑定

将2个数组中的2个对象组合成一个循环?

将2个数组中的2个对象组合成一个循环?

素胚勾勒不出你 2021-05-19 17:13:14
我正在通过使用javascript组合西装对象数组和卡片对象数组来创建一副卡片(卡片对象数组)。我正在使用forEach循环遍历西装,并且嵌套的是卡片的映射循环。console.log返回正确的对象以推送到新数组,但是.push()仅使用最后一个西装和最后一个卡来追加组合的对象。我在哪里错呢?我尝试了多种不同的循环和方法来添加到新数组中而没有运气。Console.log()返回正确的值,但是我无法将正确的组合对象推送到新数组。  // Deck of Cardsvar suits = [  { suit: "clubs", color: "black" },  { suit: "spades", color: "black" },  { suit: "hearts", color: "red" },  { suit: "diamonds", color: "red" }];var family = [  { name: "2", value: 2 },  { name: "3", value: 3 },  { name: "4", value: 4 },  { name: "5", value: 5 },  { name: "6", value: 6 },  { name: "7", value: 7 },  { name: "8", value: 8 },  { name: "9", value: 9 },  { name: "10", value: 10 },  { name: "J", value: 10 },  { name: "Q", value: 10 },  { name: "K", value: 10 },  { name: "A", value: 1 },];var deck = new Array();suits.forEach(function (x) {  var arr = family.map((y) => {    var obj = Object.assign(x, y);    console.log(obj);    deck.push(obj);    return obj;  });    console.log(arr);});console.log(deck);
查看完整描述

3 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

尝试Object.assign({}, x, y)代替Object.assign(x, y)。当前,您正在通过将y的所有属性添加到x中来操纵它。


// Deck of Cards

var suits = [

    {suit: "clubs",color: "black"},

    {suit: "spades",color: "black"},

    {suit: "hearts",color: "red"},

    {suit: "diamonds",color: "red"}    

];


var family = [

    {name: "2",value: 2},

    {name: "3",value: 3},

    {name: "4",value: 4},

    {name: "5",value: 5},

    {name: "6",value: 6},

    {name: "7",value: 7},

    {name: "8",value: 8},

    {name: "9",value: 9},

    {name: "10",value: 10},

    {name: "J",value: 10},

    {name: "Q",value: 10},

    {name: "K",value: 10},

    {name: "A",value: 1},

];


var deck = new Array();


suits.forEach(function(x){


    var arr = family.map( (y) => {

        var obj = Object.assign({}, x, y); 

        deck.push(obj);

        return obj; 

    });


});


console.log(deck);


查看完整回答
反对 回复 2021-05-27
?
慕娘9325324

TA贡献1783条经验 获得超4个赞

如果可以使用flatmap,那么它可以变得非常简单:


const suits = [{ suit: "clubs", color: "black" }, { suit: "spades", color: "black" }, { suit: "hearts", color: "red" }, { suit: "diamonds", color: "red" }]

const family = [{ name: "2", value: 2 }, { name: "3", value: 3 }, { name: "4", value: 4 }, { name: "5", value: 5 }, { name: "6", value: 6 }, { name: "7", value: 7 }, { name: "8", value: 8 }, { name: "9", value: 9 }, { name: "10", value: 10 }, { name: "J", value: 10 }, { name: "Q", value: 10 }, { name: "K", value: 10 }, { name: "A", value: 1 }]


const deck = suits.flatMap(s => family.map(f => ({...s, ...f})))


console.log(deck)

附带说明一下,订购西服杆/钻石/心形/黑桃似乎有很强的约定(大概是布里奇的惯例)。用英语很容易记住,因为它们是字母。


查看完整回答
反对 回复 2021-05-27
  • 3 回答
  • 0 关注
  • 179 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信