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

查看:219
本文介绍了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

(for 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天全站免登陆