我可以减少我的代码使用循环变量或阵列

问题描述:

现在的重复代码问题已解决,但执行if条件函数moveHorse正在重复执行。请帮忙。 function moveHorse(horseId)我可以减少我的代码使用循环变量或阵列

); interval = setInterval(function(){moveHorse('horseID');},20);

} 

现在的重复代码的问题已经解决,但执行的if条件函数moveHorse正在repeteadly执行时。请帮忙。

+1

只需通过马进的功能,而不是写'无功horse4 =的document.getElementById(“horse4”);'所有的地方。 – Carcigenicate

通行证在作为函数参数的元素ID,那么你就可以重构代码 -

// TODO: rename your local variable name because now it doesn't need to be horse4, right? 
function horseUp(horseElementId) { 
    var horse = document.getElementById(horseElementId); 
    // do the rest 
} 

function horseDown(horseElementId) { 
    var horse = document.getElementById(horseElementId); 
    // do the rest 
} 

function horseleft(horseElementId) { 
    var horse = document.getElementById(horseElementId); 
    // do the rest 
} 

要使用该功能,通过元素ID

horseUp('horse4'); 
horseLeft('horse2'); 

+0

上一个问题已解决,但现在我已将horseID的值作为间隔函数中的horse1。但是horseID的值在moveHorse函数中传递到horseDown,而在horseDown函数的IF条件中不传递。并且moveHorse函数的重复执行是由于变量的函数名称相同。请帮忙! –

因为这似乎是一个不同的马正在发生变化的只是一部分,只是通过在例如:

var horse4 = document.getElementById('horse4'); 

function horseUp(horse, moving) { 

    var horseTop = horse.offsetTop; 
    var random = Math.random() * 2.7 + 2; 

    horse.style.top = horseTop - 0.5 * random + 'px'; 

    if (horseTop <= window.innerHeight * 0.05) { 
     clearInterval(interval4); 
     interval4 = setInterval(moving, 10); 
    } 
} 

还有一些其他变量,如interval4,你需要弄清楚,但是这应该给你一个总的想法。

可以使用OOP:

function Horse(id) { 
    this.el = document.getElementById(id); 
} 

Horse.prototype={ 
    move(x,y){ 
    this.el.offsetTop+=(this.y=typeof y !=="undefined"?y:this.y); 
    this.el.offsetLeft+=(this.x=typeof x !== "undefined"?x:this.x); 
    }, 
    up(){ 
    this.move(0,0.5*Math.random() * 2.7 + 2* + 'px'; 
    }, 
    down(){ this.move(0,- 0.5* Math.random() * 2.4 + 2);}, 
    left(){ this.move(0.5* Math.random() * 2.4 + 2,0);}, 
    right(){ this.move(- 0.5* Math.random() * 2.4 + 2,0);}, 
    setInterval(){ 
    this.interval=setInterval(_=>this.move(),10); 
    } 
} 

使用这样的:

var horse4=new Horse("horse4"); 
horse4.setInterval(); 
horse4.left();