2011-12-27 5 views
0

당신이 나를 도울 수 있습니다. ID로 개체 값을 반환하는 전역 개체 및 함수를 만들려면 어떻게해야합니까?자바 스크립트 | 객체, 배열 및 함수

예 :

나는 새로운 기능을 만들 수있는 방법
var chat = { 
    data : { 
     friends: {} 
    } 
} 

.... 
/* 
JSON DATA RETURNED: 
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]} 
*/ 

onSuccess: function(f){ 
    chat.data.friends = {}; 
    for(var i=0; i< f.users.length;i++){ 
     chat.data.friends.push(f.users[i]) 
    } 
} 

(그것은 friend_id에 의해 값을 반환합니다)? 사용

get_data_by_id: function (what, friend_id) { 

/*obj.what = getfrom_globalobject(chat.data.friends???)*/ 
} 

예 :

var friend_name  = get_data_by_id(name, 62); 
var friend_username = get_data_by_id(username, 62); 
var friend_avatar = get_data_by_id(thumb, 62); 
+1

나는 당신이 ... 대신 코드의 비트를 copypasting의 그냥 "이해없이 어딘가에서 copypasted"비명 소리도 첫 조각을 프로그램하는 방법을 배우는 것이 좋습니다. – Esailija

답변

1

시도 :

get_data_by_id: function (what, friend_id) { 
    return chat.data.friends[friend_id][what]; 
} 

...하지만 그것을 사용 좋아 :

var friend_name  = get_data_by_id('name', 62); 

... 그리고로 매핑을 설정합니다

for(var i=0; i< f.users.length;i++){ 
    chat.data.friends[f.users[i].friend_id] = f.users[i]; 
} 
+0

감사! 그것은 작동합니다. – user889349

+0

@ user889349 환영합니다 :) – sje397

1

당신은 객체에 .push() 수 없습니다. 객체는 key => value 매핑, 그래서 당신은 당신이 정말 그냥 숫자 키를 사용하여 목록을 원하는 경우, char.data.friends[somekey] = f.users[i];

를 사용 x5fastchat.data.friends를 배열해야 : 당신이 액세스 할 수 있기를 원하므로, 그러나 x5fastchat.data.friends = [];

friend_id에 의한 요소는 다음을 수행하십시오

onSuccess: function(f){ 
    x5fastchat.data.friends = {}; 
    for(var i=0; i< f.users.length;i++){ 
     chat.data.friends[f.users[i].friend_id] = f.users[i] 
    } 
} 

get_data_by_id: function (what, friend_id) { 
    obj[what] = chat.data.friends[friend_id][what]; 
} 

주 대신 obj[what] 원래 obj.what : obj.what를 작성할 때, what는 문자열처럼 취급, 그래서 동일입니다 obj['what']으로 -하지만 그것은 함수 인수이므로 obj[what]이 필요합니다.

+0

니스 ... 무엇 : getfrom_globalobject? 이것은 기능입니까? – user889349

+1

아니면 obj [what] = chat.data.friends [friend_id] [what]? – user889349

0

는 한 번 봐 다음 코드. HTML 파일에 붙여 넣기 만하면됩니다. "go"를 클릭하면 결과를 볼 수 있습니다. 내가 너를 정확하게 이해하지 못했다면 나에게 알려줘. :

<script> 

myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" } 


function go() 
{ 

    findField(myObj, ["field2"]) 
    findField(myObj, ["field1","key1a"]) 
} 


function findField(obj, fields) 
{ 

    var myVal = obj; 
    for (var i in fields) 
    { 
     myVal = myVal[fields[i]] 
    } 

    alert("your value is [" + myVal + "]"); 

} 
</script> 


<button onclick="go()">Go</button> 
0

친구 개체를 ID와 이름으로 가져 오는 대신 사용하는 것이 좋습니다.

DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]} 

// simple data store definition 
Store = {items:{}}; 
NewStore = function(items){ 
    var store = Object.create(Store); 
    store.items = items || {}; 
    return store 
}; 
Store.put = function(id, item){this.items[id] = item;}; 
Store.get = function(id){ return this.items[id]; }; 
Store.remove = function(id){ delete this.items[id]; }; 
Store.clear = function(){ this.items = {}; }; 

// example 
var chat = { 
    data : { 
     friends : NewStore() 
    } 
} 

// after data loaded 
chat.data.friends.clear(); 
for(var i = 0; i < DATA.users.length; i += 1){ 
    var user = DATA.users[i]; 
    chat.data.friends.put(user.friend_id, user); 
} 

getFriend = function(id){ return chat.data.friends.get(id); } 

var friend = getFriend(66); 
console.log(friend.name); 
console.log(friend.username); 
console.log(friend.thumb);