mongodb 및 ajax 호출을 사용하여 데이터를 검색하고 있습니다. 자바 스크립트 객체로 바뀌면 때때로 HTML을 생성하는 데 사용하는 속성이 존재하지 않습니다. 이 호출에 봐 :N 레벨에서 객체 속성 호출하기 자바 스크립트
$.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 수 또는 속성. 때로는 정의되지 않았으며 앱이 다운됩니다.
이 메서드는 개체에서 속성을 호출하고 정의되지 않은 경우 빈 문자열을 반환합니다. 이 메소드를 호출하는 몇 가지 예는 (첫 번째 개체이고, 다른 하나는 재산) 다음 경우, 첫 번째 방법의 get_property에서
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(mention,"text")
get_property(mention,"user","name")
get_property(mention,"picture")
아래와 속성은 존재합니까, 어떻게 부르세요 ?? 나는 객체와 배열이 같은 자신의 propertys 것 : 객체
params = ["user","name"]
을하지만, 나는 다음과 같이 호출 할 수 없습니다 : 필요 (
object.["user","name"]
'get_property' 함수의'if' 문을'checkNested' 함수의'for' 루프로 대체하십시오. 그런 다음'true' 또는'false'를 리턴하는 대신 찾은 값 또는'' "를 리턴하십시오. –
하지만 checkNested 함수는 값이 아니라 true 또는 false를 반환합니다. –
내가 설명했던 것을 수행하는 [답변] (http://stackoverflow.com/a/13345966/1689607). 그러나 다시, 당신은 * if 문 전체를 대체하고 다른 함수로부터'for' 문을 그 자리에 놓습니다. 그런 다음 * 반환 값을 변경하여 더 이상 true 또는 false를 반환하지 않습니다. –