I would like to know how to pass varible in map function using javascript
var obj = ["Singapore", "Malaysia"]
var pr = ["SG", "MY"] // need to pass value to map function
render(){
obj.map((val, pr)=>{
return html`
<p id="pr">val</p>
}
As jonrsharpe already stated in a comment: The second parameter of the function you hand to the map
function is the index of the object you use map on. You can read about the parameters in the docs .
So a solution would be to use this index to access the values of another array like this:
var obj = ["Singapore", "Malaysia"]
var pr = ["SG", "MY"] // need to pass value to map function
render(){
obj.map((val, index) => {
abbr = pr[index];
// abbr will get the values "SG", "MY" whatsoever
}
You just have to watchout that your obj and pr arrays have the same size and are sorted correctly.
As the others have mentioned the second argument to map
is the index
of the element of the current iteration, and it doesn't look like you need it in your example. However, what you might find useful is placing the names/code into the same object and map
ping over an array of those objects instead. That way related information stays together.
var arr = [{ name: 'Singapore', code: 'SG' }, { name: 'Malaysia', code: 'MY' }];
class App extends React.Component {
render() {
return arr.map(({ name, code }) => {
return html`<p id="${code}">${name}</p>`;
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.