解决[对象对象]问题

时间:2019-04-18 10:18:19

标签: javascript

我正在尝试使用Js中的模块来分离关注点,一切顺利,除了我想显示系统时间,我也这样做了,但是当我输出它时,我得到了一个[object Object]字符串,以及什么事实证明,我确实拥有正确的系统,这是对的,这是我在控制台登录interCtrl.getTheTime时获得的系统时间,这是屏幕截图:

enter image description here

这是我的代码,可以帮助您更好地理解:

JS:

var controller = (function(interCtrl, UICtrl) {

  //1.get the time
  setInterval(document.querySelector(".Time").innerHTML = interCtrl.getTime(),100);
  // console.log(interCtrl.getTime());
  //2.get the date
  document.querySelector(".subDate").innerHTML = interCtrl.date();

  };


  document.querySelector(".add__btn").addEventListener("click", ctrlAddPlans);

  document.addEventListener("keypress", function(e) {
    if (e.keyCode === 13) {
      ctrlAddPlans();
    }
  });

})(internalController);


var internalController = (function() {

  //some code
  function getTheDate() {
    var newDate;
    var d = new Date();
    var day = d.getDate();
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    // var x=1;
    if (month.toString().length < 2) {
      month = " 0" + month + " ";
    }
    var date = " %11%/%04%/%2019%";
    newDate = date.replace("%11%", day + " ");
    newDate = newDate.replace("%04%", month);
    newDate = newDate.replace("%2019%", " " + year);
    return newDate;
  }

  function getTheTime() {
    //.get the timeDiv
    // const timeDiv =
    //.get the time (h,m,s)
    var date = new Date();
    var hours = date.getHours();
    if (hours.toString().length < 2) {
      hours = `0${hours}`;
    }
    var mins = date.getMinutes();
    if (mins.toString().length < 2) {
      mins = `0${mins}`;
    }
    var seconds = date.getSeconds();

    return {
      time: hours+ " : "+ mins+" : "+seconds
    };

  }



  return {
    date: function getDate() {
      return getTheDate();
    },
    getTime: function getTime() {
      return getTheTime();
    }
  };


})();

我看到了这个问题,但没有帮助我what does [object Object] mean?

因此请提供任何帮助,并先谢谢您

1 个答案:

答案 0 :(得分:2)

getTime函数的输出是一个对象。要使其输出字符串,可以从以下位置更改其return语句

    return {
      time: hours+ " : "+ mins+" : "+seconds
    };

    return hours + " : " + mins+" : " + seconds;

或者,或者,如果要使其成为对象,则必须访问其time属性以获取值。喜欢

var timeObj = interCtrl.getTheTime();
var timeString = timeObj.time;