简体   繁体   中英

Can someone explain to me why this var is undefined?

I've been trying this simple code.

var d = new Date();
x = ["Sunday","Monday","Tuesday", "Wednsday", "Friday", "Saturday", "Sunday"]; 
d.getDay();
document.getElementById("demo").innerHTML = "Today is " + x[d]; 

But it doesn't work. It says Today is undefined

Instead it works like this document.getElementById("demo").innerHTML ="Today is " x[d.getDay()];

But why?

The method Date#getDay that you use in d.getDay() returns the number of the day, but doesn't change d , which is still the date object. To use the value returned by the getDay() method, you need to assign the result to a variable, or use it directly, like you do in x[d.getDay()]; .

Because you are using the object d using the bracket notation [] to access an array index that doesn't exist, you get undefined as result.

Since, you don't actually need the date, just assign the day directly to d :

var d = new Date().getDay()

Example:

 var d = new Date().getDay(); var x = ["Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"]; document.getElementById("demo").innerHTML = "Today is " + x[d];
 <div id="demo"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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