Reputation: 59
I am using .map method and I am getting the second argument as the current value instead of the index so basically its upside down
I consoled log the currentValue and it shows currentValue, I consoled log "i" and it prints undefined
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>
);
});
};
Upvotes: 0
Views: 215
Reputation: 507
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)
})
Because Array.from({length: 9})
gives you an array of 9 undefined
so when you use a map over the array, it will print undefined
as value, and 0-8 as index.
Upvotes: 5
Reputation: 413
If you are looking for alternate solution then try this. Otherwise above explanations are good enough :)
Array.from(Array(9).keys()).map(callback)
Upvotes: 0
Reputation: 6838
There is nothing wrong with the output.
You are creating a new array of 9 elements. The elements' value is initially undefined
, so when you use map
over them and console.log
the value of the first argument to map
(in your case i), they will be undefined.
And the second argument to map
, in your case currentValue
, is actually the index of the current value.
So, how you name your variables in your code is very confusing. Change them and everything looks normal:
const az = Array.from({length: 9}).map((currentValue, i) => {
console.log(i)
console.log(currentValue)
})
And one more thing, the first argument to the map
function isn't actually the current value but the current element of the array that you are performing map
on. The element could be another array, or an object. So, better to call it currentElement
, or something similar, that denotes that this is an element of the array and could be of any type.
Upvotes: 0