Hi I was trying to print an array variables on my console of my browser. Firstly I tried to print the below
var name = [ 'john', 'mark'];
var years = new Array(1990,1969,1948);
console.log(name[1]);
console.log(name.length);
and got the output as below
And finally I added the names
instead of name
as shown in below code
var names = [ 'john', 'mark'];
var years = new Array(1990,1969,1948);
console.log(names[1]);
console.log(names.length);
and output for the above code is shown in this
Can I know whats the difference between?
You are colliding with the built in window.name
property
window.name will convert all values to their string representations by using the toString method.
window.name will provide the name of you current window. More info: https://www.oreilly.com/library/view/javascript-the-definitive/0596000480/re335.html
The variable name
in your example is treated like it was a String, even after you tried to change it to an array.
Print the variables name
and names
and you will see the differences.
Output of console.log(name): "john,mark"
Output of console.log(names): ["john", "mark"]
Edit: Reason was provided by @charlietfl
Reason:
window.name
Actually when you defines a variable with
var
keyword andname
name , you are using thewindow.name
field of the browser DOM.
And when you defines the name
with var
keyword it can not override the string
type and behavior of the window.name
to array
and your value will be saved in its as string » "john,mark"
Proof:
console.log(window.name); { var name = [ 'john', 'mark']; console.log(window.name); console.log(name); console.log(name[1]); console.log(name.length); }
Solution:
let
If you want to have a name
variable other than window.name you should use let
keyword instead of var
:
{ let name = [ 'john', 'mark']; console.log(name); console.log(name[1]); console.log(name.length); }
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.