我必须编写一个程序,让用户使用 prompt()
输入对象的名称,然后列出该对象的所有属性。
我类(class)中的许多学生都在使用 eval()
,但我了解到使用这种方法并不是一个好主意。
所以我尝试编写更好的代码,但我无法完成它。我最大的问题是当用户编写 this.object
和编写 object.object.object
并且必须显示第三个对象的属性时。
var x = prompt("Object?");
x = x.toLowerCase();
if (x === "window") {
x = window;
load_table();
} else if (window[x]) {
x = window[x];
load_table();
} else if (x[0] === "t" && x[1] === "h" && x[2] === "i" && x[3] === "s" && x[4] === ".") {
x = x.split('.');
x = x[1];
load_table();
} else {
document.write("Error Message.");
}
有什么建议吗?
最佳答案
尝试这样的事情:
var x = prompt("Object?");
// x = x.toLowerCase(); // not including, what if the object has a capital in its name?
x = x.split('.');
if (x[0] == 'this') {
x.shift(); // remove this, as it refers to window anyways
}
var theObj = window; // start with the global object
for (var i = 0; i < x.length; i++) {
theObj = theObj[x[i]];
if (theObj == undefined) break;
}
变量 theObj
将包含您的最终值。
关于javascript - 如何识别一个字符串是否是一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26531220/