你好我有一个很奇怪的问题,没有多大意义。我有一个字符串变量,我想搜索具有相同名称的对象(这也是一个对象)的属性。像这样:
var ObjectProperty; /// multi-layer object
var PropertyName; //string
如果对象中的 PropertyName 匹配,我想返回它。示例代码:
OBJECT:
Bird.Raven = {
Name:"Raven",
Color:"Black",
}
//Object
Bird.Duck = {
Name:"Duck",
Color: "Gray",
}
//Object
Bird.Cardinal = {
Name:"Cardinal",
Color: "Red",
}//Object
///ObjectProperty sample.
我想在“鸟”中找到的钥匙:
var Cardinal = "Cardinal"; //string
///PropertyName sample.
我正在使用的当前函数,假设“n”是我要搜索的 PropertyName 变量:
var searchBirds = function(n) {
for(var key in Bird) {
var keyName = key.toString();
if(keyName == n){
console.log("bird " + key + " has been found.");
console.log(typeof key);//RETURNS STRING
return key;
}
else{
console.log(n + " could not be found")
};
}
}
为什么它应该是一个对象时返回一个字符串?我怎样才能让它作为对象返回密钥?怎么了?Vanilla Javascript 首选。
感谢您的帮助,我希望这是有道理的!