我目前正在学习Javascript,并且从课程中退出脚本,只是玩弄自己目前所学的知识。

为了了解我是否了解“控制流”和“功能”参数,我决定制作一个Container Dock日志。这个想法是根据容器的到达和停靠时间来记录它们:


新容器是指已停靠少于30分钟的容器。
旧容器是指停靠至少30分钟的容器。


基于这些信息,我编写了以下代码:



// Containers type: Old and New based on 30min arrivals.

const containerDocked = (container,arrivalTime) => {
  newContainer = arrivalTime < 30;
  oldContainer = arrivalTime >= 30;
  if (newContainer) {
    console.log('New Container: ' + container + ' just arrived ' + arrivalTime + 'min ago.' );
  }
    else if (oldContainer) {
      console.log('Docked Container: ' + container + ' has been docked for ' + arrivalTime + 'min.');
    }
    else if(container === false && arrivalTime === true) {
      console.log('A container that arrived '+ arrivalTime + 'mins ago, has not been logged!!!');
    }
    else if(container === true && arrivalTime === false) {
      console.log('Container: ' + container + 'has not been logged!!!');
    }
    else {
      console.log('Container has not been logged!!!!');
    }
};

containerDocked('John', 24);
containerDocked('Elizabeth', 57);
containerDocked('Harry', 30);
containerDocked('Mike');





它似乎确实有效,但是如您所见,按照我的if / else规则,“ Mike”没有登录。您能指出我做错了什么吗?

最佳答案

这是解决方法

container === truearrivalTime === true问题



// Containers type: Old and New based on 30min arrivals.

const containerDocked = (container,arrivalTime) => {
  newContainer = arrivalTime < 30;
  oldContainer = arrivalTime >= 30;
  if (newContainer) {
    console.log('New Container: ' + container + ' just arrived ' + arrivalTime + 'min ago.' );
  }
    else if (oldContainer) {
      console.log('Docked Container: ' + container + ' has been docked for ' + arrivalTime + 'min.');
    }
    else if(!container && arrivalTime) {
      console.log('A container that arrived '+ arrivalTime + 'mins ago, has not been logged!!!');
    }
    else if(container && !arrivalTime) {
      console.log('Container: ' + container + 'has not been logged!!!');
    }
    else {
      console.log('Container has not been logged!!!!');
    }
};

containerDocked('John', 24);
containerDocked('Elizabeth', 57);
containerDocked('Harry', 30);
containerDocked('Mike');

07-24 16:12