如何定位对象数组中的属性

时间:2019-10-31 08:28:59

标签: javascript

我正在使用Vanilla JS构建一个简单的纸牌游戏。

我有一个纸牌对象数组:

let cards = [
    {value: "4", suit: "Hearts", weight: 4, cardFace: "🂴"},
    {value: "K", suit: "Clubs", weight: 10, cardFace: "🃟"}
]

如何将所有cardFace属性定位到cards中的任何索引,以便可以在HTML文档中显示它们?

我希望我有道理。

3 个答案:

答案 0 :(得分:1)

  

您可以使用Array.from方法

let cards = [
    {value: "4", suit: "Hearts", weight: 4, cardFace: "🂴"},
    {value: "K", suit: "Clubs", weight: 10, cardFace: "🃟"}
];

let result = Array.from(cards, card => card.cardFace);
console.log(result);

答案 1 :(得分:0)

您可以直接直接访问它们:

let cards = [
    {value: "4", suit: "Hearts", weight: 4, cardFace: "🂴"},
    {value: "K", suit: "Clubs", weight: 10, cardFace: "🃟"}
]

console.log(cards[0].cardFace);
console.log(cards[1].cardFace);

您还可以在基于索引的for循环中执行此操作:

let cards = [
  {value: "4", suit: "Hearts", weight: 4, cardFace: "🂴"},
  {value: "K", suit: "Clubs", weight: 10, cardFace: "🃟"}
];

for (let i = 0; i < cards.length; i++) {
  console.log(cards[i].cardFace);
}

另一个选择是for ... of循环,它更易于阅读imo。这也使用ES6的对象解构

let cards = [
  {value: "4", suit: "Hearts", weight: 4, cardFace: "&#127156;"},
  {value: "K", suit: "Clubs", weight: 10, cardFace: "&#127199;"}
];

for (const { cardFace } of cards) {
  console.log(cardFace);
}

您还可以从cards创建一个只有颜色值的新数组:

let cards = [
    {value: "4", suit: "Hearts", weight: 4, cardFace: "&#127156;"},
    {value: "K", suit: "Clubs", weight: 10, cardFace: "&#127199;"}
]

const colors = cards.map(card => card.cardFace);

console.log(colors); // ["&#127156;", "&#127199;"]

答案 2 :(得分:0)

您可以使用访问对象字段。像这样:

object.field

您可以使用:

let cards = [
    {value: "4", suit: "Hearts", weight: 4, cardFace: "&#127156;"},
    {value: "K", suit: "Clubs", weight: 10, cardFace: "&#127199;"}
]

cards.forEach(card => {
  console.log(card.cardFace);
})