简体   繁体   中英

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...

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"

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.

 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>

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