简体   繁体   English

JavaScript变量上的点符号

[英]Dot Notation on JavaScript variables

dateNow = new Date()
dateGet = dateNow.getDay()
document.write(dateGet.toDateString())

Why is this document.write(date11.toDateString()) not allowed in JavaScript... date11 is a variable. 为什么JavaScript中不允许使用document.write(date11.toDateString()) ... date11是一个变量。 It gives me an error of "toDateString() is not a function" 它给我一个错误“ toDateString()不是函数”

Presuming you meant to write dateGet and not date11 in your question: 假设您要在问题中写dateGet而不是date11

The problem is that dateGet is not a Date instance-- it is a number that was returned from the getDay() Date method. 问题在于dateGet不是Date实例-它是从getDay() Date方法返回的数字

 const dateNow = new Date() const dateGet = dateNow.getDay() console.log(dateNow instanceof Date); // true console.log(typeof dateNow.getDay); // function console.log(dateGet instanceof Date); //false console.log(typeof dateGet); // number console.log(typeof dateGet.toDateString); // undefined document.write(dateGet.toDateString()) // 🙁 

Since dateGet is not an instance of Date but is actually a number, it has no such method as .toDateString , so when you attempt to call this non-existent method an error is thrown. 由于dateGet不是Date的实例,而实际上是一个数字,因此它没有.toDateString这样的方法,因此,当您尝试调用此不存在的方法时,将引发错误。

toDateString() is a function for Date objects. toDateString()是Date对象的函数。 dateGet or date11 are actually integers because that's what getDay() returns, so that's by design: toDateString() is not a function of integers . dateGet或date11实际上是整数,因为那是getDay()返回的结果,所以这是设计使然:toDateString()不是整数的函数。 You can either `document.write(dateGet) and that'll return an integer for the day of the week. 您可以`document.write(dateGet),然后返回星期几的整数。 If you want "monday" or "tuesday", etc. then you'll need to create a small array of days and match to the dateGet. 如果要“星期一”或“星期二”等,则需要创建一小部分天并与dateGet匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM