javascript:如何使用forEach访问数组中的下一个索引?

时间:2018-12-21 22:23:52

标签: javascript

我有一个可能缺少数字的排序数组:例如public class WriteFile { public static void main(String[] args) { String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now()); File logFile = new File(timeLog); try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile))) { System.out.println("File was written to: " + logFile.getCanonicalPath()); bw.write("Hello world!"); } catch (IOException e) { e.printStackTrace(); } } } ,我将把缺少的数字推入一个单独的数组中。我试图使用forEach循环,因为我没有返回任何东西,但是我需要将数组中的元素与数组中的下一个元素进行比较。 我知道我可以使用For循环并通过对变量执行[3,4,5,7,8]来访问它,以便获得下一个索引,但是它如何与forEach一起使用?

2 个答案:

答案 0 :(得分:2)

如果通常要这样做,则可以在遍历过程中计算间隙,并在reduce()循环中制作缺失数字的数组。像这样:

let arr = [-2,3,4,5,7,8,10,15]

let missing = arr.reduce((arr, item, index, self) => {
    let gap = self[index+1] - item - 1 // will be NaN with index + 1 is out of range
    return gap > 0 
        ? arr.concat(Array.from({length: gap}, (_, i) => i+1 + item))
        : arr
   
}, [])

console.log(missing.join(', '))

答案 1 :(得分:0)

就这么简单:

const arr = [3,4,5,7,8];

arr.forEach((item, index, array) => {
    const next = array[index + 1];
    console.log(next);
});