[英]Dot Notation on JavaScript variables
dateNow = new Date()
dateGet = dateNow.getDay()
document.write(dateGet.toDateString())
為什么JavaScript中不允許使用document.write(date11.toDateString())
... date11
是一個變量。 它給我一個錯誤“ toDateString()不是函數”
假設您要在問題中寫dateGet
而不是date11
:
問題在於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()) // 🙁
由於dateGet
不是Date
的實例,而實際上是一個數字,因此它沒有.toDateString
這樣的方法,因此,當您嘗試調用此不存在的方法時,將引發錯誤。
toDateString()
是Date對象的函數。 dateGet或date11實際上是整數,因為那是getDay()
返回的結果,所以這是設計使然:toDateString()不是整數的函數。 您可以`document.write(dateGet),然后返回星期幾的整數。 如果要“星期一”或“星期二”等,則需要創建一小部分天並與dateGet匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.