我是 JavaScript 新手。我有一个问题
我的 Java 代码:
public void checkArray(int a, int b) {
int[]days = new int[]{5, 15, 25};
int[]hours = new int[]{6, 8, 7};
ArrayList<Interger> result = new ArrayList<>();
for (int i = 0; i < days.length-1; i++) {
if (days[i] < a && b < days[i+1]) {
result.add(hours[i]);
} else if (days[i] > a && days[i] < b) {
result.add(hours[i]);
if (i > 0) {
result.add(hours[i-1]);
}
}
如何使用 Lodash _.each
在 JavaScript 中编写此代码?我在 JavaScript 代码中找不到像 [i] 这样的变量,所以我无法检查条件 [if (days[i] < a && b < days[i+1])]
我的 JavaScript 代码:
_.each(days, day => {
//TODO something
})
最佳答案
来自 Lodash documentation :
Iterates over elements of
collection
and invokesiteratee
for each element. Theiteratee
is invoked with three arguments:(value, index|key, collection)
. Iteratee functions may exit iteration early by explicitly returningfalse
.
这意味着你可以简单地做:
_.each( days, function( day, i ){
});
所以你的整个代码变成:
var days = [5, 15, 25];
var hours = [6, 8, 7];
var result = [];
_.each( days, function( day, i ){
if( days[i] < a && b < days[i+1] ){ // days[i] == day
result.push( hours[i] );
} else if( days[i] > a && days[i] < b ){
result.push( hours[i] );
if( i > 0 ){
result.push( hours[i-1] );
}
}
})
这是一个jsFiddle进行实验。
关于javascript - 如何在 Lodash _.each 中获取数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54470353/