React Native - 如何在map函数中传递索引

3
我有一个映射函数,可以重复动态地创建组件。假设它是这样的:
renderBoxes() {
    return Array.map(data => this.myFunction(indexOfThisArray));
} 

如何传递数组的索引?这样每次调用“myFunction”函数时,它都可以获取索引值。


1
至少你为我节省了一些时间,哈哈。 - Bikram Thapa
3个回答

15

使用map函数时,它会将当前元素的索引作为第二个参数,整个数组作为第三个参数提供。

renderBoxes() {
    return Array.map((data, index, array) => this.myFunction(index));
} 

了解有关Array.prototype.map的更多信息。


4

map的语法如下:

var new_array = arr.map(function callback(currentValue, index, array) {
    // Return element for new_array
}[, thisArg])
来源。在回调函数中,您可以将索引作为第二个参数找到。

2
只需向箭头函数传递第二个参数 (data, index) 即可。
renderBoxes() {
    return Array.map((data, index) => this.myFunction(indexOfThisArray));
} 

.map的签名

var new_array = arr.map(function callback(currentValue, index, array) {
    // Return element for new_array
}[, thisArg])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接