2014-04-24 3 views
1

세 개의 객체를 만들었습니다. 각 객체는 서로 다른 배열을 가지고 있습니다.자바 스크립트 - 개체를 어떻게 호출합니까?

var redmeat = {options: ["beef", "steak", "kangaroo"]}, 
    whitemeat = {options: ["chicken", "turkey"]}, 
    fish = {options: ["salmon", "tuna"]}; 

그런 다음 HTML에서 세 가지 해당 옵션이있는 선택 필드를 만들었습니다.

<select name="meat-type"> 
    <option value="redmeat">Red meat</option> 
    <option value="whitemeat">White meat</option> 
    <option value="fish">Fish</option> 
</select> 

이제 사용자가 필드를 선택할 때마다 내 콘솔에 올바른 배열을 표시 할 수 있기를 원합니다. (예를 들어, 붉은 고기를 선택하면, 콘솔은 "쇠고기", "스테이크", "캥거루"를 기록합니다.)

$('select[name=meat-type]').change(function(){ 
    var e = $("select[name=meat-type] option:selected").val(); 
    function updatefield (e){ 
     console.log(e); //this works, easy. 
     f = e.options; //but this doesn't work, return as undefined 
     console.log(f); 
    };   
    updatefield(e); 
}); 

그래서 질문입니다; 어떻게 객체를 호출할까요?

+3

문구 "call the object"는별로 의미가 없습니다. – Pointy

+0

'e'는 정의한 객체가 아니라 문자열입니다. –

+0

예 'e'는 문자열이지만 문제는; 그 문자열을 객체로 바꿀 수있는 방법이 있습니까, 그렇다면 e.options를 할 수 있을까요? – user3540018

답변

2

대신 그 변수를 선언, 객체를 구축 : 다음

var meats = { 
    redmeat: {options: ["beef", "steak", "kangaroo"]}, 
    whitemeat: {options: ["chicken", "turkey"]}, 
    fish: {options: ["salmon", "tuna"]} 
}; 

:

f = meats[e].options; 
+0

고마워요,하지만 앞으로 더 많은 고기 종류를 추가 할 수 있기를 원합니다. 그러므로 나는 붉은 맷돌, 흰자미, 물고기를 모두 별도의 물건으로 유지할 수 있기를 원합니다. 또한 각 객체에 더 많은 키와 속성을 추가 할 수 있기를 원합니다. – user3540018

+0

그들은 분리 된 객체입니다. 다른 것을 추가하려면, 다른 것을 말하면 나중에 다음과 같이 쓸 수 있습니다 :'meats.other = {options : [ "tofu"]}' – chuckj

3

먼저 당신이 개체를 수정하고 하나의 객체에 넣어해야합니다.

그런 다음 쉽게 객체 키를 호출하고 값을 얻을 수 있습니다. 여기

var meatObj = { 
    redmeat: ["beef", "steak", "kangaroo"], 
    whitemeat: ["chicken", "turkey"], 
    fish: ["salmon", "tuna"] 
}; 

$('select[name=meat-type]').change(function(){ 
    console.log(meatObj[this.value]); 
}); 

모든 답변에 감사하지만 내가 찾던 해답의 종류는 평가 방법이었다, 내가 아픈 후반 응답

0

죄송 위의 코드에 대한 fiddle입니다.

는 그래서는 어떻게 해 모든 ...

f = eval(e); //and then... 
    g = f.options; 

완료!

관련 문제