简体   繁体   English

如何将字符串和函数参数混合到变量中

[英]How to mix strings and function parameters into a variable

So I've been needing something like this for a bit now but never been able to find something that suits my needs, Most likely I'm searching the wrong things!所以我现在一直需要这样的东西,但从来没有找到适合我需要的东西,很可能我正在寻找错误的东西!

My goal is to put a parameter from a function like foobar("test") and put the parameter plus some pre-written strings from the function and plus them together and therefore becoming a pre-existing variable...我的目标是从 foobar("test") 之类的函数中放入一个参数,并将该参数加上该函数中的一些预先编写的字符串并将它们加在一起,从而成为一个预先存在的变量...

I think I'm explaining very poorly... but hopefully, the code example gets a better explanation...我想我的解释很差……但希望代码示例能得到更好的解释……

I've tried a few simple things that were obvious won't work so I most likely don't need to show what I did...我已经尝试了一些明显不起作用的简单事情,所以我很可能不需要展示我做了什么......

var text1 = "this is text"

function foo(id) {
    object.innerHTML = "text" + 1 // Then plus those together and make it set it to the variable text1
}

foo(1)

Expected: I would want it to write in the object "this is text" because it makes text and the id variable aka a 1 into text1 which is a variable with the string of "this is text"预期:我希望它写在对象“this is text”中,因为它使 text 和 id 变量又名 1 到 text1 中,这是一个带有“this is text”字符串的变量

Actual Results: Obviously that won't work I don't even need to write it to be able to find out that this won't work... Just an example to better explain...实际结果:显然这行不通我什至不需要写它就能发现这行不通......只是一个更好地解释的例子......

Hopefully you can help, thx!希望能帮到你,谢谢!

var text1 = "this is text"

function foo(id) {
    object.innerHTML = window['text'+id];}

foo(1)

You have to use eval function.您必须使用 eval 函数。

 var text1 = "this is text" var text2 = "this is text2" function foo(id) { console.log(eval('text'+id)); } foo(2)

As I explained in my comment, taking the question at face value leads to recommending something that is usually unnecessary and error prone, and should therefore be avoided.正如我在评论中所解释的,从表面上看问题会导致推荐通常不必要且容易出错的内容,因此应该避免。

There are much more readable alternatives, like creating an object and using its keys and [] notation:还有更多可读的选择,比如创建一个对象并使用它的键和[]表示法:

 var texts = { example: "this is text", message: "Hello World!" }; function foo(id) { someDiv.innerHTML = texts[id]; } foo("message");
 <div id="someDiv"></div>

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

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