首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Javascript -如何重构代码以使其看起来更整洁

Javascript -如何重构代码以使其看起来更整洁
EN

Stack Overflow用户
提问于 2020-09-08 16:16:33
回答 4查看 83关注 0票数 0

我有一个看起来有点原始的函数,我想知道是否有人有任何解决方案来改善这个函数的外观。我能把这个原始的循环if()... if()...改成看起来更干净更好的东西吗?

代码语言:javascript
运行
复制
function drawPlayers () {
    if (players[0].nick != null) {
        let player1Img = new Image(SQUARE, SQUARE)
        player1Img.onload = function() {
            ctx.drawImage(player1Img, LEFT_LINE + players[0].x * SQUARE, UPPER_LINE + players[0].y * SQUARE, this.width, this.height)
        }
        player1Img.src = "sprites/player1.png"
    }
  
    if (players[1].nick != null) {
        let player2Img = new Image(SQUARE, SQUARE)
        player2Img.onload = function() {
            ctx.drawImage(player2Img, LEFT_LINE + players[1].x * SQUARE, UPPER_LINE + players[1].y * SQUARE, this.width, this.height)
        }
        player2Img.src = "sprites/player1.png"
    }
  
    if (players[2].nick != null) {
        let player3Img = new Image(SQUARE, SQUARE)
        player3Img.onload = function() {
            ctx.drawImage(player3Img, LEFT_LINE + players[2].x * SQUARE, UPPER_LINE + players[2].y * SQUARE, this.width, this.height)
        }
        player3Img.src = "sprites/player1.png"
    }
  
    if (players[3].nick != null) {
        let player4Img = new Image(SQUARE, SQUARE)
        player4Img.onload = function() {
            ctx.drawImage(player4Img, LEFT_LINE + players[3].x * SQUARE, UPPER_LINE + players[3].y * SQUARE, this.width, this.height)
        }
        player4Img.src = "sprites/player1.png"
    }
}
EN

Stack Overflow用户

发布于 2020-09-08 16:33:26

代码语言:javascript
运行
复制
function drawPlayers() {
  players.forEach((player, idx) => {
    if (player.nick != null) {
      // uncomment following comment block and delete this comment
      /*
      var img = new Image(SQUARE, SQUARE)
      img.onload = () => {
        ctx.drawImage(img, LEFT_LINE + player.x * SQUARE, UPPER_LINE + player.y * SQUARE, this.width, this.height)
      };
      img.src = "sprites/player"+(idx+1)+".png";
      */
      console.log(idx, player.nick, "sprites/player"+(idx+1)+".png");
    }
  });
}

var players=[{nick:"abe"},{},{nick:"chuck"},{nick:"dick"}];
drawPlayers();

票数 2
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63789840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档