简体   繁体   English

Javascript-如何调用对象?

[英]Javascript - How do I call the object?

As you can see I've created three objects, each one has a different array. 如您所见,我已经创建了三个对象,每个对象都有一个不同的数组。

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

Then, in the HTML I've created a select field, with three corresponding options. 然后,在HTML中,我创建了一个选择字段,其中包含三个相应的选项。

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

Now, whenever the user selects the field, I want to be able to display the correct array in my console. 现在,无论何时用户选择该字段,我都希望能够在控制台中显示正确的数组。 (For instance, when red meat is selected, the console will log "beef", "steak", "kangaroo".) (例如,当选择红肉时,控制台将记录“牛肉”,“牛排”,“袋鼠”。)

$('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);
});

So the question is; 所以问题是; how do I call the object? 我怎么称呼物体?

First you need to modify your object and put them into single object. 首先,您需要修改您的对象并将其放入单个对象。

After that you can easily call the object key and get it's value. 之后,您可以轻松地调用对象键并获取其值。

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

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

Here is the fiddle for above code 这是上面代码的小提琴

Instead of declaring those variables, build an object: 与其声明这些变量,不如建立一个对象:

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

Then: 然后:

    f = meats[e].options;

sorry for the late response I was sick, thank you for all your answers but the kind of answer that I was looking for was the eval method. 抱歉,我生病了很晚,谢谢您的所有回答,但我一直在寻找的评估方法是评估方法。

So all I gotta do is... 所以我要做的就是...

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

done! 完成!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM