欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Javascript 变量相关基础

程序员文章站 2021-12-17 21:58:48
...
来自JSDG:

[quote]The types can be divided into two groups: primitive types and reference types.

Numbers, boolean values, and the null and undefined types are primitive.

Objects, arrays, and functions are reference types.

A primitive type has a fixed size in memory.

Variables hold the actual values of primitive types, but they hold only references to the values of reference types.

The JavaScript keyword null is a special value that indicates no value. null is usually considered a special value of object typea value that represents no object.


undefined is returned when you use either a variable that has been declared but never had a value assigned to it or an object property that does not exist.

null and the undefined value are distinct, the == equality operator considers them equal to one another.

When the undefined value is used in a Boolean context, it converts to false.
When used in a numeric context, it converts to NaN.
when used in a string context, it converts to "undefined".[/quote]

变量分为两个类型,原始类型和引用类型。

原始类型:数字、布尔、null、undefined
引用类型:对象、数组、函数

字符串是特例,拥有原始类型和引用类型的特点

一个变量持有原始类型的实际值,但是只持有引用类型的引用:
var a = [1,2,3];  // Initialize a variable to refer to an array
var b = a; // Copy that reference into a new variable
a[0] = 99; // Modify the array using the original reference
alert(b); // Display the changed array [99,2,3] using the new reference


null是特殊的类型,对象类型的数据默认值就是null,代表“没有对象”。

undefined意味着这个变量要么没有声明,要么就是指向一个并不存在的对象属性

JS中null==undefined的值是true,要用===才能区别这两个特殊值


有相关自动转换的情况:
[img]/upload/attachment/122449/868b8141-2337-39b4-8095-52bac1e95943.png[/img]

在函数内部申明的局部变量一定要用var,否则就会默认得到一个全局变量
相关标签: JavaScript