完全不使用很容易做到eval
:
function getValue(path) {
var target = this;
path.split('.').forEach(function (branch) {
if (typeof target === "undefined") return;
target = (typeof target[branch] === "undefined") ? undefined : target[branch];
});
return target;
}
如果您想从window
您开始获取属性,只需调用getValue("path.to.property")
. 如果您想从其他一些根对象开始,请使用getValue.call(rootObject, "path.to.property")
.
该函数也可以适用于将根对象作为可选的第一个参数,但想法保持不变。
看到它在行动。
重要提示:这在 Internet Explorer < 9 上不起作用,因为Array.prototype.forEach
它不存在。你可以用
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisPointer */) {
var len = this.length;
if (typeof fun != "function") throw new TypeError();
var thisPointer = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
fun.call(thisPointer, this[i], i, this);
}
}
};
}