我怎样才能更好地编写代码,使我的代码看起来不那么业余呢?

How can I have coded this better so my code doesn't look so amateurish?

本文关键字:代码 看起来 我的 余呢 更好      更新时间:2023-09-26

这段代码获取8个div,并根据分配给div的时间值在屏幕上进行比赛。我怎样才能更好地编写代码,使我的代码看起来不那么业余?

我知道我应该在for循环中使用硬编码的8而不是timeArray。length不可用,因为我正在使用splice从数组中删除项。

$(document).ready(function() {
var timeArray = new Array(3,4,5,6,7,8,9,10);
var shortestTime = timeArray[7];
var fastestPony = {};
var index;
var pony = {
    name: "pony",
    raceTime: -1,
    selected: ""
};
//change the color of the pony when the user clicks on it
$('.pony').bind('click', function() {
    $('.pony').removeClass('selectedPony');
    $(this).addClass('selectedPony');
    //get the pony that the user selected
    pony.selected = $(this);
});
$('#startButton').click(function() { 
    if (pony.selected == "") {
        alert("Please click the pony you think will win the race.");
    }
    else {
        for (i = 1; i <= 8; i++) {
        //get a random number from the timeArray
            index = Math.floor(Math.random() * timeArray.length);
            pony.raceTime = timeArray[index];
            //pull the random race time number out of the array 
            //so it can't be assigned to another horse
            timeArray.splice(index, 1);
            //get the fastest pony
            if (pony.raceTime < shortestTime) {
                shortestTime = pony.raceTime;
                fastestPony = $('#pony' + i);
            }
            //award the winner after the ponies have reached the finish line
            if (i == 8) {
                fastestPony.addClass('winner').append(' - Winner!');
            }
            //send the horses on their way to race!
            $('#pony' + i).animate({left: '320px'}, pony.raceTime * 1000);
        }
    }
});
//reset the ponies back to the starting line by reloading the page
$('#resetButton').click(function() {
    document.location.reload(true);
});
});

这确实是一个偏好和挑剔的问题,但既然你问了…

我听说on(...)方法在大多数圈子中是首选的:

$('.pony').on('click', function() {

$('#startButton').on('click', function() {

当然,这取决于你使用的是什么版本的jQuery,可能完全是主观的