[英]Condition inside forEach
I have two arrays: 我有两个数组:
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
I must use their elements to compute another one inside a forEach. 我必须使用它们的元素来计算forEach中的另一个元素。
_.forEach(firstArray, (data, i) => {
myValue: firstArray[i] + secondArray[i]
});
This works fine. 这很好。 But I want to ignore the last element of the second array all the time.
但是我想一直忽略第二个数组的最后一个元素。 So in this case, for
i = 3
the result should be 4
, not 4+8
, ignoring the last value of the second array. 因此,在这种情况下,对于
i = 3
,忽略第二个数组的最后一个值,结果应为4
,而不是4+8
。
I know that using an if
statement wouldn't work but is there a way to do it? 我知道使用
if
语句不起作用,但是有办法吗?
I mean inside the forEach, removing the last element before the function doesn't work in this case. 我的意思是在forEach内部,在这种情况下函数无法正常工作之前删除最后一个元素。
UPDATE : I received some good answers but all of them were using something different than forEach
. 更新 :我收到了一些很好的答案,但是所有答案都使用了与
forEach
不同的方法。 I would like to know if there is a way to do it with this function or not. 我想知道是否有一种方法可以使用此功能。
You can just check if i
is the last element of the second array using array.length
. 您可以使用
array.length
检查i
是否是第二个数组的最后一个元素。
I don't really understand your forEach
code, but you could use ternary operators in it: 我不太了解您的
forEach
代码,但是您可以在其中使用三元运算符:
_.forEach(firstArray, (data, i) => {
myValue: firstArray[i] + (i === secondArray.length - 1 ? 0 : secondArray[i])
});
Use map
使用
map
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
var output = firstArray.map( ( s, i, ar ) => s + (i == ar.length - 1 ? 0 : secondArray[i] ) );
UPDATE: I received some good answers but all of them were using something different than forEach.
更新:我收到了一些很好的答案,但所有答案都使用了与forEach不同的方法。 I would like to know if there is a way to do it with this function or not.
我想知道是否有一种方法可以使用此功能。
using forEach
, you would need another array to capture the sum 使用
forEach
,您将需要另一个数组来捕获总和
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
var myValue = [];
firstArray.map( ( s, i, ar ) => myValue.push( s + (i == ar.length - 1 ? 0 : secondArray[i] ) ) );
now myValue
is 现在
myValue
是
[6, 8, 10, 4]
[6、8、10、4]
Hence map
seems to be a less-verbose approach. 因此,
map
似乎是一种不太冗长的方法。
You could reduce and map the arrays. 您可以缩小并映射数组。
var firstArray = [1, 2, 3, 4], secondArray = [5, 6, 7, 8], result = [firstArray, secondArray].reduce((a, b) => a.map((v, i) => v + b[i])); console.log(result);
I would do this: 我会这样做:
firstArray = [1, 2, 3, 4];
secondArray = [5, 6, 7, 8];
for (let i = 0; i < firstArray.length; i++){
if(i === firstArray.length - 1) {
myValue = firstArray[i];
} else {
myValue = firstArray[i] + secondArray[i]
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.