如何在对象值中使用动态变量?

时间:2021-02-22 19:42:50

标签: javascript object

是否可以在对象值中使用动态变量? (非财产)

errors = { 'small_age':`${age} is too small`}

age = 17;
if (age < 18) {
   alert(errors.small_age)
} 

3 个答案:

答案 0 :(得分:1)

JavaScript 是一个 Dynamic Programming Language。 (阅读有关 Dynamic Type Systems 的更多信息)

您的代码是正确的(即使您没有包含定义 var age 的代码)。这是fiddle for it。因您使用的支持 Template Literals 的 JavaScript 版本而异。

答案 1 :(得分:1)

您可以使用函数作为对象中的值,然后传递您想用作参数的变量,这样在错误消息中使用的值就更明显了。

playPass("I have $235");   // I have $764

预期的警报消息

const errors = { 'small_age': (age) => `${age} is too small` }

const age = 17;
if (age < 18) {
   alert(errors.small_age(age))
}

答案 2 :(得分:0)

感谢@Diego_Sanches,我就这样解决了jsfiddle

const errors = { 
  'too_young': (n) => `${n} is too young`,
  'too_short': (n) => `${n} is too short`,
  'too_heavy': (n) => `${n} is too heavy`,
  //there thousant err msgs, and didnot want to seperate each of them for related functions...  
  }

function check_age(n){
  if (n < 18) alert(errors.too_young(n)) 
}

function check_height(n){
  if (n < 180) alert(errors.too_short(n))
}

function check_weight(n){
  if (n > 90) alert(errors.too_heavy(n))
}

check_age(17);
check_height(150);
check_weight(120);
相关问题