javascript 字符串到语句

javascript string to statements

当我们将字符串连接到对象时,它会自动将所有值转换为字符串。

有什么方法可以不将其转换为字符串或者可以将字符串转换回语句。

我正在尝试做一些事情,比如如果我输入长度,它会加到字符串变量中并计算字符串的长度。

var property = prompt("Add the Property");
var myObject = "This is the String";
var propertyCombinedWithObject = myObject + "." + property;
console.log(propertyCombinedWithObject);

结果是一个字符串 "This is the String".length 而不是计算字符串的数量。

我试过了

eval(propertyCombinedWithObject)

但是没用。

要访问对象的 属性,可以使用方括号表示法:

var property = prompt("Add the Property");
var myObject = "This is the String";
var propertyCombinedWithObject = myObject[property];
console.log(propertyCombinedWithObject);

是的,您正在寻找的是带有括号符号的 JS 对象。

var property = prompt("Add the Property");
var myObject = "This is the String";
console.log(myObject[property]);