简体   繁体   中英

Passing array of strings to a function in a string literal

When I pass an array of strings and an index to an onclick event, the callback function receives the parameters from the first two values of the array as a number instead of the array and the index.

I have tried to convert it to an array using the Array.from function.

 let presentantes = ["28411", "199904", "214966", "16226"]; console.log('presentantes', presentantes); //presentantes (4) ["28411", "199904", "214966", "16226"] let id = 1 let listNominated = `<li onClick="cargaPresentantes(${presentantes}, ${i})">` function cargaPresentantes(presentantes, id) { console.log('presentantes', presentantes); console.log('id', id) //presentantes 28411 //id 199904 }

I was expecting to get an array ["28411", "199904", "214966", "16226"] and the index 1

You cannot pass the parameters in that way... you should create a “onclick listener function” and then associate it to the “li” element.

Actually template literals work something like this - If the variable which is passed to the placeholder is not a string(an array in this case) then it CONVERTS it to string. So in your code the value of listNominated becomes '28411,199904,214966,16226,1' and thus it takes the first two arguements ie 28411 and 199904.

As Andrea said I had to add an onclcik listener function. To do this, I had to append the string literal to the document first.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM