简体   繁体   English

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

[英]How can I get index of the value inside forEach loop?

Absolutely NewBee 绝对是NewBee

How Can I find out the index of the value and not the value itself inside forEach loop Currently I have following code which just gives my the value of userAnswers : 我如何才能找到值的索引而不是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)
    );

In the above example I want to get index which is 2 and not the value (1) itself ? 在上面的示例中,我想获取为2索引,而不是值(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) , findingTotal is not used too tempArr.push(index) ,也没有使用findTotal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM