示例: 洗牌一副
// program to shuffle the deck of cards // declare card elements const suits = ["Spades", "Diamonds", "Club", "Heart"]; const values = [ "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", ]; // empty array to contain cards let deck = []; // create a deck of cards for (let i = 0; i < suits.length; i++) { for (let x = 0; x < values.length; x++) { let card = { Value: values[x], Suit: suits[i] }; deck.push(card); } } // shuffle the cards for (let i = deck.length-1; i > 0; i--) { let j = Math.floor(Math.random() * i); let temp = deck[i]; deck[i] = deck[j]; deck[j] = temp; } console.log('The first five cards are:'); // display 5 results for (let i = 0; i < 5; i++) { console.log(`${deck[i].Value} of ${deck[i].Suit}`) }
输出
The first five cards are: 4 of Club 5 of Diamonds Jack of Diamonds 2 of Club 4 of Spades
在上面的程序中,
suits 和
values 变量包含一张卡片的元素。
嵌套的
我们需要创建一副卡片,其中包含每个 suits 以及所有 values。因此,第一个 for
循环用于创建一副纸牌。
for
循环遍历所有 suits,第二个 for
循环遍历 values。然后,创建元素并将其添加到 deck
数组中。
数组元素作为对象存储为:
[{Value: "Ace", Suit: "Spades"},{Value: "2", Suit: "Spades"}.....]
第二个
for
循环用于洗牌。
Math.random()
生成一个随机数。
Math.floor()
通过将值减小到最接近的整数值来返回数字。
在 0 和 51 之间生成一个随机数,并交换两张卡片位置。
第三个
for
循环用于显示新牌组中的前五张牌。