两个数组,长度相同。如果第一个数组值等于true,则从第二个数组获取值

时间:2018-02-14 14:51:27

标签: javascript

我有两个数组。它们的长度始终相同。如果userEmotions[index]值为true,我需要将userTimeData[index]值添加到变量:

var userEmotions = [false, true, false, true],
    userTimeData = [140, 320, 730, 50],
    userPercentage = 0;

// e.g add 320 and 50 to userPercentage:
// userPercentage == 370

我如何实现这一目标?

5 个答案:

答案 0 :(得分:2)

您可以使用for循环:



var userEmotions = [false, true, false],
  userTimeData = [140, 320, 730],
  userPercentage = 0;

for (i = 0; i < userEmotions.length; i++) { //loop the length of the array
  if (userEmotions[i]) { // check userEmotions is true
    userPercentage += userTimeData[i]; // if it is add userTimeData to percentage
  }
}

console.log(userPercentage);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以将Array#indexOf用作第一个单值,或将零用作默认值。

var userEmotions = [false, true, true],
    userTimeData = [140, 320, 730],
    userPercentage = userTimeData[userEmotions.indexOf(true)] || 0;

console.log(userPercentage);

要获取值数组,可以过滤值。

var userEmotions = [false, true, true],
    userTimeData = [140, 320, 730],
    userPercentages = userTimeData.filter((_, i) => userEmotions[i]);

console.log(userPercentages);

答案 2 :(得分:1)

OP想要替代方法,所以:

&#13;
&#13;
userEmotions = [false, true, false],
userTimeData = [140, 320, 730],
userPercentage = userEmotions
    .map(x => x ? 1 : 0)
    .map((x, i) => x * userTimeData[i])
    .reduce((a,b) => a+b);

console.log(userPercentage);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

为什么过度设计它,一个简单的for循环解决了你的问题 -

var userEmotions = [false, true, false],
    userTimeData = [140, 320, 730],
    userPercentage = 0;

for (i = 0; i < userEmotions.length; i++) {
  if (userEmotions[i]) {
    userPercentage += userTimeData[i];
  }
}

console.log(userPercentage);

答案 4 :(得分:0)

你可以试试这个:

for(let i = 0 ; i < userEmotions .length ; i++){
   if(userEmotions[i]){
       userPercentage = userTimeData[i]
   }
}

让我知道它是否对你有帮助:)。