在我的for element of array
循环中,我想访问当前元素之外的元素。具体而言,上一个或下一个元素。我也希望这能跨越第一个/最后一个元素障碍。如何实现?
即。给出:
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
是我希望避免的事情。
谢谢
答案 0 :(得分:5)
您应该使用forEach
循环并使用第二个参数index。
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]}`)
}
答案 1 :(得分:1)
您可以使用常规的initQuizsForm(){
const array = [];
this.quizs.forEach((obj: Quiz) => {
array.push(
this.formBuilder.group({
id: obj.id,
category: obj.category,
questions: this.formBuilder.array(this.initQuestionForm(obj.questions))
})
);
});
return array;
}
for (let i = 0; i < len; i++)
答案 2 :(得分: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])
}
答案 3 :(得分:1)
您可以使用forEach
。回调函数的第三个参数是数组。因此,您可以destructure来获得第[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)
})
答案 4 :(得分:1)
我希望您需要
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]);
}
}