小编jer*_*ern的帖子

异步函数中未定义睡眠?

我目前正在做一个记忆游戏项目。我正在尝试实现的一个功能是在两秒后翻转卡片而不是让它们立即翻转。

let openCards = [];

function cardActions(card) {
    // prevent function from adding two classes over and over again 
    if (!(card.classList.contains('open'))) {
        // display the card's symbol 
        card.className += ' open';
        card.className += ' show';
        // add card to list of open cards
        openCards.push(card);
        if(openCards.length === 2) {
            if(openCards[0].innerHTML === openCards[1].innerHTML) {
                // add the match class
                Array.from(openCards).forEach(function(card){
                    card.className += ' match';
                });
                console.log('match');
                // empty open cards
                openCards = [];
            } else {
                Array.from(openCards).forEach(function(card) {
                    // add the mismatch …
Run Code Online (Sandbox Code Playgroud)

javascript sleep async-await

0
推荐指数
1
解决办法
9392
查看次数

如何使用.forEach正确访问数组中的对象?

对于一个测验,我得到了一个包含对象的数组:

var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }
];
Run Code Online (Sandbox Code Playgroud)

我的工作是使用.forEach方法遍历数组中的对象.好吧,我基本上攻击它并制作了一个迭代变量来帮助我使用索引来访问每个对象.

var i = 0;
donuts.forEach(function(donutSummary) {

var donut = donuts[i].type;
var cost = donuts[i].cost;

console.log(donut + " donuts cost $" + cost + " each");
i = i + 1;
});
Run Code Online (Sandbox Code Playgroud)

在我的代码顶部,我声明并为我的索引分配了一个变量i.我知道必须有一种更好的方法来访问这个数组中的对象.

谁能告诉我在不使用迭代变量的情况下执行此操作的正确方法是什么?

谢谢!

javascript arrays object

-1
推荐指数
1
解决办法
94
查看次数

标签 统计

javascript ×2

arrays ×1

async-await ×1

object ×1

sleep ×1