如何在forEach循环中获取值的索引?

问题描述 投票:0回答:1

绝对是NewBee

我如何在forEach循环中找到值的索引而不是值本身目前我有以下代码,它只给出了userAnswers的值:

    correctAnswers: [], // [1, 2, 3, 1, 2, 1, 3, 3, 4, 3]
    userAnswers: [],    // [1, 2, 1, 1, 2, 1, 3, 3, 4, 3]

    let tempArr = [];
    const findingTotal = userAnswers.forEach(
        (value, index) =>
            value === correctAnswers[index]
                ? (Total += 1)
                : tempArr.push(value)
    );

在上面的例子中,我想获得2的索引,而不是值(1)本身?

javascript
1个回答
1
投票
correctAnswers: [], // [1, 2, 3, 1, 2, 1, 3, 3, 4, 3]
userAnswers: [],    // [1, 2, 1, 1, 2, 1, 3, 3, 4, 3]

let tempArr = [];
let Total = 0; 
userAnswers.forEach(
    (value, index) =>
        value === correctAnswers[index]
            ? (Total += 1)
            : tempArr.push(index)
);

tempArr.push(index),findTotal也没用过

© www.soinside.com 2019 - 2024. All rights reserved.