简体   繁体   English

将字符串数组传递给字符串文字中的 function

[英]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.当我将字符串数组和索引传递给 onclick 事件时,回调 function 从数组的前两个值接收参数作为数字而不是数组和索引。

I have tried to convert it to an array using the Array.from function.我尝试使用 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我期待得到一个数组["28411", "199904", "214966", "16226"]和索引 1

You cannot pass the parameters in that way... you should create a “onclick listener function” and then associate it to the “li” element.您不能以这种方式传递参数……您应该创建一个“onclick 侦听器函数”,然后将其关联到“li”元素。

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.因此,在您的代码中,listNominate 的值变为“28411,199904,214966,16226,1”,因此它采用前两个参数,即 28411 和 199904。

As Andrea said I had to add an onclcik listener function.正如 Andrea 所说,我必须添加一个 onclcik 监听器 function。 To do this, I had to append the string literal to the document first.为此,我必须首先将字符串文字 append 写入文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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