Javascript forEach() 通过数组:如何获取上一项和下一项? [英] Javascript forEach() through an array: how to get the previous and next item?

查看:147
本文介绍了Javascript forEach() 通过数组:如何获取上一项和下一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个对象数组,例如:

Let's say we have an array of objects like:

var fruits = [ {name:"banana", weight:150},{name:"apple", weight:130},{name:"orange", weight:160},{name:"kiwi", weight:80} ]

我想遍历水果,每次告诉当前、上一个和下一个水果的名称.我会做类似的事情:

I want to iterate through fruits and tell each time the name of the current, the previous and the next fruit. I would do something like:

fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
console.log("Previous: " + item[index-1].name);  
console.log("Next: " + item[index-1].name);
});

但显然它不适用于下一个和上一个项目......有什么想法吗?

But obviously it doesn't work for next and previous items... Any idea?

请注意,我不想使用经典的 for 循环

Please note that I do not want to use the classic for loop

(对于 i=0; i

非常感谢!

推荐答案

它不起作用,因为 item 不是数组所以我们不能写 item[index-1].name.相反,我们需要使用 Fruits[index-1] .此外,数组的第一个元素不会有前一项,最后一个元素不会有下一项.下面的代码片段应该适合您.

Its not working because item is not an array so we cannot write item[index-1].name. Instead, we need to use fruits[index-1] .Also, the first element of the array will not have the previous item and the last element will not have next item. Code snippet below should work for you.

var fruits = [{
    name: "banana",
    weight: 150
}, {
    name: "apple",
    weight: 130
}, {
    name: "orange",
    weight: 160
}, {
    name: "kiwi",
    weight: 80
}]

fruits.forEach(function(item, index) {
    console.log("Current: " + item.name);
    if (index > 0) {
        console.log("Previous: " + fruits[index - 1].name);
    }
    if (index < fruits.length - 1) {
        console.log("Next: " + fruits[index + 1].name);
    }
});

这篇关于Javascript forEach() 通过数组:如何获取上一项和下一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆