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) 对于一个测验,我得到了一个包含对象的数组:
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.我知道必须有一种更好的方法来访问这个数组中的对象.
谁能告诉我在不使用迭代变量的情况下执行此操作的正确方法是什么?
谢谢!