简体   繁体   English

将声明的变量分配给数组javascript中的字符串

[英]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? 1)我如何在字符串中插入变量,以便在调用值对时动态更新它?

2) How would I do the same using JSON? 2)如何使用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. 当某些变量更改时,您不能具有JSON结构或字符串“自动”更新。 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"); 然后,您将执行诸如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: 如果您不想为每个模板编写函数(即,如果有很多模板),则可以使用String.replace如下所示:

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. JavaScript中的字符串是原始类型,它按值传递。 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.namelanguageStrings.car ,您想要的所有三个字符串将自动采用您刚刚设置的新值:

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). 您不必一直手动调用applyTemplate ,就像@qxz的答案一样(不过,我并不是说他错了)。

Also, please notice that even name and car are not enumerable - they will not be accessed with for in , for of , or Object.keys ! 另外,请注意,甚至namecar都不是枚举值-不能通过for infor ofObject.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 . 实际上,这种反应模型在当今的MV *前端框架中已得到广泛使用,例如Vue

Regarding your second question, I didn't get it honestly. 关于你的第二个问题,我并没有坦白地说。 Just JSON.parse then it's all ordinary JavaScript, isn't it? 只是JSON.parse那都是普通的JavaScript,不是吗?

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

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