如何在js中使用带对象的eval函数?

时间:2016-12-19 09:11:27

标签: javascript eval

var obje = {hair: "yellow", eyes: "blue"};
var format = "hair + ' ' + eyes";
console.log(eval(format));

我尝试将console.log(eval(format))写入"yellow eyes"到控制台。如何在格式字符串中将"hair"更改为"obje.hair"以及从"eyes"更改为"obje.eyes"

2 个答案:

答案 0 :(得分:3)

Do not use eval

使用类似的东西:



var obj = {hair: "yellow", eyes: "blue"};
var format = "{hair} {eyes}";

// Option 1: manual replacement
var result = format.replace('{hair}', obj.hair).replace('{eyes}', obj.eyes);
console.log(result);

// Option 2: automatic replacement
var result = format;
for(var key in obj){
  result = result.replace('{' + key + '}', obj[key]);
}
console.log(result);




构建模板字符串,然后使用字符串操作替换字段。

如果您可以使用ES6,它允许template literals开箱即用:



var obj = {hair: "yellow", eyes: "blue"};
var result = `${obj.hair} ${obj.eyes}`;

console.log(result);




答案 1 :(得分:0)

使用object.key获得预期



var obje = {hair: "yellow", eyes: "blue"};
var format = "obje.hair + ' ' + obje.eyes";
console.log(eval(format));