我正在使用Vanilla JS构建一个简单的纸牌游戏。
我有一个纸牌对象数组:
let cards = [
{value: "4", suit: "Hearts", weight: 4, cardFace: "🂴"},
{value: "K", suit: "Clubs", weight: 10, cardFace: "🃟"}
]
如何将所有cardFace
属性定位到cards
中的任何索引,以便可以在HTML文档中显示它们?
我希望我有道理。
答案 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: "🂴"},
{value: "K", suit: "Clubs", weight: 10, cardFace: "🃟"}
];
for (const { cardFace } of cards) {
console.log(cardFace);
}
您还可以从cards
创建一个只有颜色值的新数组:
let cards = [
{value: "4", suit: "Hearts", weight: 4, cardFace: "🂴"},
{value: "K", suit: "Clubs", weight: 10, cardFace: "🃟"}
]
const colors = cards.map(card => card.cardFace);
console.log(colors); // ["🂴", "🃟"]
答案 2 :(得分:0)
您可以使用访问对象字段。像这样:
object.field
您可以使用:
let cards = [
{value: "4", suit: "Hearts", weight: 4, cardFace: "🂴"},
{value: "K", suit: "Clubs", weight: 10, cardFace: "🃟"}
]
cards.forEach(card => {
console.log(card.cardFace);
})