从对象方法内的数组运行console.log

时间:2012-07-13 21:34:01

标签: javascript arrays function methods

我刚刚在学校学习对象,我知道一个函数可以从一个对象内部运行,但该函数实际上被称为一个方法,我的方法有一个数组,我喜欢让一个特定的目标在通过更改全局变量来控制console.log。可以这样做吗?在最后一个console.log - >所有我得到的都是未定义的。在“+ worker.getLocation.myLocation”;所以在所有现实中我都试图改变全局变量var myLocation = 0以在getLocation方法中输出不同的myLocation。

var myLocation = 0

var worker = {
    realName:       "Willson",
    title:          "Assistant Maintenance Supervisor",
    maintenance:    true,
    vehicals:       ["2008 Dodge Caliber SRT-4", "2012 Jeep Wrangler Unlimited"      ],
    getLocation:    function () { 
        myLocation [0] = "Villas at Sunrise Mountain";
        myLocation [1] = "Reno Villas"; 
        myLocation [2] = "lost"; 
        myLocation [3] = "back home";
    }
};

console.log(worker.realName + " is a " + worker.title + " and drives a " + worker.vehicals[1] + " to work."); 

var destination = {
    property: ["Villas at Sunrise Mountain", "Reno Villas", "lost", "back home"]
};

console.log ("He sold his " + worker.vehicals[0] + "." + " Today he is working at " + worker.getLocation.myLocation);

1 个答案:

答案 0 :(得分:1)

var myLocation = 0

var worker = {
    realName:       "Willson",
    title:          "Assistant Maintenance Supervisor",
    maintenance:    true,
    vehicals:       ["2008 Dodge Caliber SRT-4", "2012 Jeep Wrangler Unlimited"      ],
    getLocation:    function () { 
        var myLocationss = [];
        myLocationss [0] = "Villas at Sunrise Mountain";
        myLocationss [1] = "Reno Villas"; 
        myLocationss [2] = "lost"; 
        myLocationss [3] = "back home";

        return myLocations[myLocation];

    }
};

console.log(worker.realName + " is a " + worker.title + " and drives a " + worker.vehicals[1] + " to work."); 

var destination = {
    property: ["Villas at Sunrise Mountain", "Reno Villas", "lost", "back home"]
};

console.log ("He sold his " + worker.vehicals[0] + "." + " Today he is working at " + worker.getLocation());