Word Reserved Behavior

When creating a game with a small counter, I had an array like this:

var status = ["day","dusk","night","dawn"]; 

If I tried to access the first index of the array, I would get:

 console.log(status[0]); //yields "d" 

@monners mentioned that it could be a reserved word, so I changed the variable name to xstatus and it worked fine.

My question is: why status[0] return only the first letter of the first index?

+7
javascript arrays
source share
4 answers

You change window.status , which cannot be set to an array:

https://developer.mozilla.org/en-US/docs/Web/API/Window.status


There is some inexplicable behavior in Firefox. Although status and var status in the global scope provide references to the window.status property, var status does not smooth the array:

 status = ["meagar"]; console.log(window.status[0]); // 'm' 

against

 var status = ["meagar"]; console.log(window.status[0]); // 'meagar' 
+6
source share

Since it will save your array as a flat string, and d is the first character (position 0 ) of the string.


I believe that this happened years ago in the old Navigator status days (remember these ticker status lines). Status can only be displayed as a string --- arrays, when set to a string, are smoothed and separated by a comma (for example, var ar=['foo','bar']; alert(ar); )

+2
source share

When you do

status = [...];

You essentially write or better declare by changing the status variable in the window object.

window.status = [...];

If status set as a new variable: var status = [...] , then this will solve the problem. I know that you have the var status in your example above, but without it, this is the only way I can think that this will cause a problem.

Update

According to Felix Kling, a variable defined in the global area and not encapsulated will encounter this problem because it is a member variable in the window object.

I would suggest changing the name of the variable or encapsulating it.

0
source share

You have reassigned the variable "status" to a line starting with "d" (for example, day, twilight, or dawn).

 var status = 'day'; console.log(status[0]) // d console.log(status[1]) // a // etc... 

Strings are treated as arrays of characters, so you get access to individual characters with parentheses.

-one
source share

All Articles