gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:23:55 24 4
gpt4 key购买 nike

我有两个数组。它们的长度始终相同。如果 userEmotions[index] 值为真,我需要将 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

我该如何实现这一目标?

最佳答案

你可以使用 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);

关于javascript - 两个数组,长度相同。如果第一个数组值等于 true 从第二个数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48790026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com