简体   繁体   中英

Assigning a declared variable to a string in array javascript

Let's say I have these global variables:

var name, car;

Then I declare some values:

const languageStrings = {
    WELCOME_MESSAGE: 'Welcome #name, you have a #car',
    NAME_USER: "#name",
    CAR_USER: '#car'
};

And then I need to assign it to a function. For example:

if (firstTime){
    welcomeMsg = WELCOME_MESSAGE;
}

Now, I have two questions:

1) How would I insert a variable inside of a string so it is dynamically updated when the value pair is called?

2) How would I do the same using JSON?

You would have to make a function that returns the value of the variable.

In your case:

welcomeMessage = function(){
   return WELCOME_MESSAGE
}

and you would reference the variable with:

welcomeMessage()

So, you'd be assigning a variable as a function that returns the current value of the other variable. You get the value by calling your variable as a function.

the answer to your question on how to insert variables inside a string is:

WELCOME_MESSAGE: 'Welcome ' + name + ', you have a ' + car,

or before defining:

function mesg(name, car){
    return "Welcome" + name + ", you have a " + car;
}
mesg(bob, BMW);

in this case, the name and car is defined after.

You can't have a JSON structure or string "automatically" update when some variable changes. There are other ways to do this type of templating, though. You could create a function to create a welcome message when you need one:

function getWelcomeMessage(name, car) {
  return "Welcome "+name+", you have a "+car;
}

Then you'd do something like welcomeMsg = getWelcomeMessage("Joe", "Camry");

If you don't want to write a function for every template (ie if you have lots of them), then you could use String.replace like this:

function applyTemplate(template, params) {
  return template.replace(/#(\w+)/g, (m, name) => params[name]);
}

Example usage:

 function applyTemplate(template, params) { return template.replace(/#(\\w+)/g, (m, name) => params[name]); } const WELCOME_TEMPLATE = "Welcome #name, you have a #car"; var name = "Joe"; var car = "Camry"; var welcomeMessage = applyTemplate(WELCOME_TEMPLATE, {name, car}); console.log(welcomeMessage); 

String in JavaScript is primitive type, it's passed by value. So once a variable is assigned with a string, it will never change until you explicitly assign another value (or object reference) to it.

However, you can ask object type for help , which could make your data reactively (or dynamically, if you prefer this word) update under certain conditions.

var languageStrings = {
  WELCOME_MESSAGE: '',
  NAME_USER: '',
  CAR_USER: ''
}

Object.defineProperty(languageStrings, 'name', {
  get: function (name) {
    return this.NAME_USER
  },
  set: function (name) {
    this.NAME_USER = name
    this.WELCOME_MESSAGE = `Welcome ${this.name}, you have a ${this.car}.`
  }
})

Object.defineProperty(languageStrings, 'car', {
  get: function (car) {
    return this.CAR_USER
  },
  set: function (car) {
    this.CAR_USER = car
    this.WELCOME_MESSAGE = `Welcome ${this.name}, you have a ${this.car}.`
  }
})

Now, whenever you change languageStrings.name or languageStrings.car , all three strings you want will automatically adopt the new value you just set:

languageStrings.name = 'Leo'
languageStrings.car = 'BMW'

for (let key in languageStrings) {
  console.log(`${key}: ${languageStrings[key]}`)
}
// WELCOME_MESSAGE: Welcome Leo, you have a BMW.
// NAME_USER: Leo
// CAR_USER: BMW

You don't have to manually call applyTemplate all the time, like in @qxz's answer (I'm not saying his wrong, though).

Also, please notice that even name and car are not enumerable - they will not be accessed with for in , for of , or Object.keys ! This is great, your implementation details are concealed, no worries or confusions to other developers who use your code.

In fact, such reactive model is widely used in front-end MV* frameworks nowadays, eg Vue .

Regarding your second question, I didn't get it honestly. Just JSON.parse then it's all ordinary JavaScript, isn't it?

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