我正在使用 .map 方法,我得到第二个参数作为当前值而不是索引,所以基本上它是颠倒
的 我控制台日志当前值,它显示当前值,我控制台日志"i",它打印未定义
const Card = props => {
return Array.from({length: 9}).map((i, currentValue) => {
console.log(currentValue);
return (
<View style={{flex: 1}}>
<Image
style={{flex: 8, width: hp('50%'), height: wp('50%')}}
source={{uri: `${props.source[currentValue]}`}}
/>
<Text style={{flex: 2, backgroundColor: 'red', margin: 10}}>
{props.title[1] ? `${props.title[currentValue]}` : 'Loading'}
</Text>
<Text style={{flex: 2, backgroundColor: 'blue', margin: 10}}>
{props.rating[currentValue]}
</Text>
</View>
);
});
};
const data = Array.from({length: 9});
console.log(data); // [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
data.map((val, index) => {
console.log(val, index); // val is undefined, index is the array index (0 to 8)
})
因为Array.from({length: 9})
给你一个 9undefined
的数组,所以当你在数组上使用地图时,它会打印undefined
作为值,0-8 作为索引。
Array.map 将currentVal
参数作为第一个参数和可选参数,将index
参数作为第二个参数。
输出没有任何问题。 您正在创建一个包含 9 个元素的新数组。元素的值最初是undefined
的,因此当您在它们上使用map
并将第一个参数的值console.log
map
时(在您的例子中为 i(,它们将被undefined.
而map
的第二个参数,在你的例子中currentValue
,实际上是当前值的索引。
因此,如何在代码中命名变量是非常令人困惑的。更改它们,一切看起来都很正常:
const az = Array.from({length: 9}).map((currentValue, i) => {
console.log(i)
console.log(currentValue)
})
还有一件事,map
函数的第一个参数实际上不是当前值,而是您正在执行map
的数组的当前元素。该元素可以是另一个数组或对象。因此,最好称其为currentElement
,或类似的东西,表示这是数组的一个元素,可以是任何类型的。
如果您正在寻找替代解决方案,请尝试此操作。否则上面的解释已经足够好了:)
Array.from(Array(9).keys()).map(callback)