gpt4 book ai didi

javascript - 使用 foreach 在数组中选择正确的索引

转载 作者:行者123 更新时间:2023-12-03 01:25:24 24 4
gpt4 key购买 nike

我已经被这个问题困扰了一段时间了。我使用 forEach 循环遍历数组,并且希望在单击组件时使用相应的索引呈现正确的页面。现在我的问题是我循环遍历数组,但无法返回正确的索引,只能返回数组中的第一个索引。我希望 Pages 组件上的 startPage 属性能够从我的 newNum 变量中渲染到正确的索引。

const itemId = this.props.navigation.getParam('pk');

let newArray = this.props.moment.filter(item => {
return item.trip == itemId
});
console.log('getting moment fromt trip')
let num = Object.keys(this.props.trip[0].moments)
let newNum = num.forEach((number, index) => {
console.log(number)
return number
})

return (
// <View style={{flex:1, backgroundColor: '#F0F5F7'}} {...this.panResponder.panHandlers}>
<View style={{flex:1, backgroundColor: '#F0F5F7'}}>
<HeaderMomentComponent navigation={this.props.navigation} />
<Pages indicatorColor="salmon" startPage={newNum}>
{newArray.map((item, index) => {
console.log('this is the index')
console.log(index)
return(
<MomentContent
name={item.name}
place={item.place}
description={item.description}
tags={item.tags}
key={index}
/>
)
})}
</Pages>
</View>
);

最佳答案

根据MDN documentation (Mozilla 开发者网络),forEach 的返回值为 undefined

使用Array#map返回一个 newNum 值。

let newNum = num.map((number, index) => {
// Some logic to get a new number...
return number
})

关于javascript - 使用 foreach 在数组中选择正确的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51573741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com