Select 字符串全局变量,包括子属性
Select global variable by string, including sub-properties
在javascript中,我想select某个属性的名字,它存储在一个字符串中。我知道 window[someString]
是要走的路。它在someString = "somevariable"
时有效,但不幸的是,我的程序也会有someobject.someproperty
这样的字符串。这不起作用。
所以问题是,给定代码
someString = "one.two.three";
one = {
two: {
three: "This is the value that I want to get"
}
};
// window[someString] does not work.
,如何使用someString
的值得到one.two.three
的值,不用使用eval
?
使用split做递归的方法
var someString = "one.two.three";
var keys = someString.split('.');
one = {
two: {
three: "This is the value that I want to get"
}
};
function getinnerProperty(object, keys) {
var key = keys.shift();
if (keys.length) {
var nestedObject = object[key];
return getinnerProperty(nestedObject, keys);
} else {
return object[key];
}
}
console.log(getinnerProperty(window, keys));
你可以写一个函数,使用split
并迭代遍历对象树:
var someString = "one.two.three";
var one = {
two: {
three: "This is the value that I want to get"
}
};
function getValue(keyStr) {
var keys = keyStr.split('.');
var result = global;
for (var i = 0; i < keys.length; i++) {
result = result[keys[i]];
}
return result != global ? result : undefined;
}
getValue(someString);
在javascript中,我想select某个属性的名字,它存储在一个字符串中。我知道 window[someString]
是要走的路。它在someString = "somevariable"
时有效,但不幸的是,我的程序也会有someobject.someproperty
这样的字符串。这不起作用。
所以问题是,给定代码
someString = "one.two.three";
one = {
two: {
three: "This is the value that I want to get"
}
};
// window[someString] does not work.
,如何使用someString
的值得到one.two.three
的值,不用使用eval
?
使用split做递归的方法
var someString = "one.two.three";
var keys = someString.split('.');
one = {
two: {
three: "This is the value that I want to get"
}
};
function getinnerProperty(object, keys) {
var key = keys.shift();
if (keys.length) {
var nestedObject = object[key];
return getinnerProperty(nestedObject, keys);
} else {
return object[key];
}
}
console.log(getinnerProperty(window, keys));
你可以写一个函数,使用split
并迭代遍历对象树:
var someString = "one.two.three";
var one = {
two: {
three: "This is the value that I want to get"
}
};
function getValue(keyStr) {
var keys = keyStr.split('.');
var result = global;
for (var i = 0; i < keys.length; i++) {
result = result[keys[i]];
}
return result != global ? result : undefined;
}
getValue(someString);