繁体   English   中英

获取在 JS for of 循环中看到的上一个项目?

[英]get previous item seen in JS for of loop?

在我for element of array ,我想访问当前元素之外的元素。 具体来说,前一个或下一个元素。 我也希望这能够跨越第一个/最后一个元素障碍。 如何做到这一点?

IE。 给定:

my_fruits = ['apple', 'banana', 'grapes', 'blueberries']

for (const fruit of my_fruits) {
    // When fruit === 'banana', I want to access 'apple', 
    // when fruit === 'blueberries' I want to access 'grapes'.
    // Also when it's the last element, I want to acknowledge that and access the first. 
}

由于我在本地处理async/await的方式, .forEach是我更愿意避免的事情。

谢谢

您应该使用forEach循环并使用索引的第二个参数。

 const arr = ['apple', 'banana', 'grapes', 'blueberries'] arr.forEach((x,i) => { let prev = i > 0 ? arr[i - 1] : null; let next = i < arr.length ? arr[i + 1] : null; console.log(`current:${x} next:${next} previous: ${prev}`) }) 

如果你不想使用forEach你可以使用for..in 但是请注意,除了数组上的索引之外,你没有添加任何属性。

 const arr = ['apple', 'banana', 'grapes', 'blueberries'] for(let i in arr){ console.log(`current:${arr[+i]} next:${arr[+i+1]} previous: ${arr[+i-1]}`) } 

你可以使用常规for (let i = 0; i < len; i++)

 let my_fruits = ['apple', 'banana', 'grapes', 'blueberries']; for (let i = 0, len = my_fruits.length; i < len; i++) { if (i == 0) { console.log("I am at first iteration. The last item is : "+ my_fruits[len - 1]); } if (i > 0) { console.log("I have now : " + my_fruits[i] + " and I have access to " + my_fruits[i - 1]); } if (i + 1 == len) { console.log("I am at last iteration. The first item is : "+ my_fruits[i - 1]); } } 

You can access the index of the current element. 

 var my_fruits = ['apple', 'banana', 'grapes', 'blueberries'] for (const [index,value] of my_fruits.entries()) { if(index) console.log(my_fruits[index-1]) } 

你可以使用forEach 回调函数的第三个参数是数组。 因此,您可以对其进行解构以获得[i-1][i+1]

 const my_fruits = ['apple', 'banana', 'grapes', 'blueberries'] my_fruits.forEach((item, i, { [i-1]: prev, [i+1]: next }) => { console.log(item, prev, next) }) 

我希望你需要什么

const my_fruits = ['apple', 'banana', 'grapes', 'blueberries']

for (let fruit in my_fruits) {

  fruit = parseInt(fruit);

   if (! my_fruits[fruit + -1]) {

      console.log(my_fruits[0] + " => " + my_fruits[fruit + my_fruits.length - 1]);

   } else {

      console.log(my_fruits[fruit] + " => " + my_fruits[fruit + -1]);

    }
}

 const arr = ['apple', 'banana', 'grapes', 'blueberries'] arr.forEach((x,i) => { let prev = i > 0? arr[i - 1]: null; let next = i + 1 < arr.length? arr[i + 1]: null; console.log(`current:${x} next:${next} previous: ${prev}`) })

我在上面使用了 Maheer Ali 的代码,但我不得不做出改变。 我把i + 1 < arr.length而不是i < arr.length因为否则它总是返回 true (索引,从 0 开始,总是小于数组的长度,如果它存在的话)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM