在 N 级 javascript 中调用对象属性 [英] calling object properties in N levels javascript
问题描述
我正在使用 mongodb 和 ajax 调用来检索数据.当谈到 javascript 对象时,我用来生成 html 的属性有时不存在.看看这个电话:
I'm using mongodb and ajax calls to retrieve data. When it turns to javascript object, the properties that I use to generate html sometimes don't exist. Look at this call:
$.ajax({
url: 'api/v1/mention/'+id,
type: "GET",
dataType: "json",
data : {login : "demo"},
success: function(mention) {
display_mention_text(mention.texto);
}
});
在这种情况下,我调用的是mention.texto,但可以是mention.picture 或任何属性.有时它是未定义的并使应用程序崩溃.
In this case i'm calling mention.texto, but could be mention.picture or any properties. Sometimes it is undefined and crashes the app.
这个方法从一个对象调用一个属性,如果它是 undefined ,则返回一个空字符串.调用此方法的一些示例(第一个是对象,另一个是属性):
This method calls a property from a object and if its undefined , return an empty string. Some examples for calling this method(the first one is an object, the other are properties):
get_property(mention,"text")
get_property(mention,"user","name")
get_property(mention,"picture")
方法定义如下:
function get_property(obj){
var args = Array.prototype.slice.call(arguments),
obj = args.shift();
if (checkNested(obj,args)) {
//what should I do here?
} else{
//the property is undefined and returns ""
"";
};
}
//check if a object has N levels of propertys
function checkNested(obj /*, level1, level2, ... levelN*/) {
var args = Array.prototype.slice.call(arguments),
obj = args.shift();
for (var i = 0; i < args.length; i++) {
if (!obj.hasOwnProperty(args[i])) {
return false;
}
obj = obj[args[i]];
}
return true;
}
在第一个方法 get_property 中,如果该属性确实存在,我该如何调用它??我会将对象和他的属性作为一个数组,如:对象
In the first method get_property, if the property do exist, how do I call that?? I would have the object and his propertys as an array like: object
params = ["user","name"]
但我不能像下面这样调用:
but I can't call like following:
object.["user","name"]
推荐答案
用 for
循环替换 get_property
函数中的 if
语句来自 checkNested
函数.然后返回找到的值或 ""
,而不是返回 true
或 false
.
Replace the if
statement in the get_property
function with the for
loop from the checkNested
function. Then instead of returning true
or false
, return the value found or ""
.
function get_property(obj){
var args = Array.prototype.slice.call(arguments),
obj = args.shift();
// Here's your 'for' loop. The 'if' statement is gone.
for (var i = 0; i < args.length; i++) {
if (!obj.hasOwnProperty(args[i])) {
return ""; // I changed the value of this 'return' statement
}
obj = obj[args[i]];
}
return obj; // I change the value of this 'return' statement
}
同样,我所做的只是将您自己的代码从一个函数复制粘贴到另一个函数,然后更改 return
语句的值.
Again, all I did was copy paste your own code from one function to the other, and change the values of the return
statements.
这篇关于在 N 级 javascript 中调用对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!