调用函数以更改对象在数组中的位置(JavaScript)

时间:2018-10-29 21:50:23

标签: javascript arrays function object

我试图弄清楚在调用函数时如何使用函数来更改对象的数组索引值,但我不知道该怎么做。这是我到目前为止的内容:

var direction = ["North","East","South","West"];

var car = function() {
/* Class Constructor */
    this.cardinal = 0;
    this.currentDirection = direction[this.cardinal];
    this.showDirection = compass;
    this.turnRight = rightTurn;

function compass()
{
    document.write("<li>" + this.name + " is going " + this.direction + ".</li>");
}
function rightTurn()
{
    if (this.cardinal < 4) {
        this.cardinal = this.cardinal + 1;
        this.showDirection();
} else {
    this.cardinal = 0;
    this.showDirection();
}    
}

} // end car constructor

pontiac    = new car();

稍后我会使用此功能调用购买

pontiac.turnRight();

该对象确实还有更多内容,但我删除了该部分以使其更易于阅读。如果需要,我可以添加其他位,但是我认为这与之无关。我知道我做错了rightTurn()函数。我使用了if else循环,因为如果汽车在西方(因为它是数组的最后一个位置),我需要它返回北。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

this.cardinal为3时,

if (this.cardinal < 4) {
    this.cardinal = this.cardinal + 1;

将其变为4,从数组中索引(有效索引为0、1、2和3)。
因此,您需要比较3:

if (this.cardinal < 3) {
    this.cardinal = this.cardinal + 1;

答案 1 :(得分:0)

请记住,this.direction必须在班级各处都this.direction。如果我是您,则可以将数组的名称从direction更改为cardinals或其他名称,以免混淆自己。

答案 2 :(得分:0)

希望这可以为您提供帮助

var car = function() {
        /* Class Constructor */
        this.directions = ["North","East","South","West"];
        this.currentIndex = 0;
        this.showDirection = compass;
        this.turnRight = rightTurn;
        this.name = "car"
        function compass()
        {   
            document.write("<li>" + this.name + " is going " + this.directions[this.currentIndex] + ".</li>");
        }

        function rightTurn()
        {   
            if (this.currentIndex == (this.directions.length-1)) {
                this.currentIndex = 0;
                this.showDirection();
            } else {
                this.currentIndex++;
                this.showDirection();
            }
        }
    } // end car constructor

    pontiac    = new car();
    pontiac.turnRight()

每次调用pontiac.turnRight()时,都会将当前方向设置为旁边的right元素,到达“西”时,您将返回“北”。