Home > Article > Web Front-end > Detailed analysis of the six basic data types in JavaScript
This article brings you relevant knowledge about the six basic data types in JavaScript. I hope it will be helpful to you.
In JavaScript, everything (variables, functions and operators) are case-sensitive. This also means that the variable name test and the variable name Test represent two different variables.
The so-called identifier refers to variables, function names and operators, or function parameters. The format rules of identifiers are as follows:
1. The first character must be a character, underscore (_) or a dollar sign ($);
2. Other characters can be letters , underscores, dollar signs and numbers;
By convention, JavaScript identifiers are written in camel case format, that is, one letter is opened in lowercase, and the first letter of the remaining words is capitalized. For example: firstChirld, myCar;
Of course, it is not mandatory to use the small camel case format for identifiers, but it can make it easier for us to understand the code. When writing, try to use the small camel case format to make it easier for others to understand your code.
The comment methods in JavaScript are divided into single-line comments and multi-line comments:
Single-line comments:
//这是一个单行注释
Multi-line comments:
/* *这是一个 *多行注释 */
In JavaScript, statements end with a semicolon; if the semicolon is omitted, the interpreter determines the end. As shown in the following example:
var sum = a + b //即使没有分号也是有效语句——不推荐 var diff = a - b; //有效语句——推荐
The variable type in JavaScript is weakly typed. The so-called weak type means that it can be used to save any type of data. In other words, each variable is just a placeholder for holding a value.
Use the var keyword when defining a variable, followed by the variable name (i.e. identifier). As shown below:
var message;
JavaScript also supports direct initialization of variables, so the value of the variable can be set while defining the variable. As shown below:
var message = "Hello world!";
One thing that must be noted is that a variable defined with the var keyword will become a local variable in the scope in which the variable is defined. In other words, if you use var to define a variable in a function, the variable will be destroyed after the function ends. For example:
function test(){ var message = "Hello"; //局部变量 } test(); console.log(message); //错误!
The reason for the error is that the variable message is defined using var in the function test(). When a function is called, variables are created and assigned values. After that, the variable is destroyed immediately, so the next line of code in the example will cause an error. However, the keyword var can be omitted as follows to create a global variable:
function test(){ message = "Hello"; //全局变量 } test(); console.log(message); //"Hello"
If the keyword var is omitted here, the message becomes a global variable. In this way, as long as the test() function is called once, the variable is defined. After the global variable is set, it can be accessed anywhere outside the function.
Although global variables can be defined by omitting the keyword var, it is not recommended because global variables defined in the local scope are difficult to maintain;
There are Several simple data types (also called basic data types): Undefined, Null, Boolean, Number, and String. There is also a complex type - Object. Object is essentially a set of unordered name-value pairs. JavaScript does not support any mechanism for creating custom types, and all values are one of these six data types.
Since JavaScript is weakly typed, there needs to be a way to detect the data type of a given variable - typeof is an operation responsible for detecting the data type of a given variable. symbol. Using the typeof operator on a value may return one of the following strings:
"undefined" - if the value is undefined;
"boolean" - if the value is a Boolean type;
"string" - if the value is a string;
"number "——If the value is a number;
"object"——If the value is an object or null;
"function"—— —If the value is a function;
The following are several examples of using the typeof operator:
var message = "hello"; console.log(typeof message); //"string" console.log(typeof(message)); //"string" console.log(typeof 95); //"number"
The operand of the typeof operator can be a variable, Can also be a numeric literal. Note that typeof is not a function, so the parentheses in this example, although they can be used, are not required.
In JavaScript, a function is an object, not a data type, so it is necessary to use typeof to distinguish functions from other objects.
The undefined type has only one value, which is the special undefined. When a variable is declared using var but is not initialized, the value of the variable is undefined. For example:
var message; console.log(message == undefined); //true var message1 = "undefined"; console.log(message1 == undefined); //true
However, the confusing point is that executing the typeof operator on an uninitialized variable will return an undefined value, and executing the typeof operator on an undeclared variable will also return an undefined value. Look at the following example:
var message; //这个变量声明之后默认取得了undefined值 //下面这个变量并没有声明 //var age; console.log(typeof message); //"undefined" console.log(typeof age); //"undefined"
Both initialized variables and declared variables return undefined. This result is logically reasonable. Because these two variables are essentially different from a technical point of view, but in fact it is impossible to perform real operations on either type of variable,
Null类型是第二个只有一个值得类型,这个特殊的值是null。从逻辑的角度来看,null值表示一个对象的空指针,而这也正是使用typeof操作符的检测null值时会返回“object”的原因,如下面的例子所示:
var message= null; console.log(message); //"object"
如果定义的对象将来用来保存对象,那么最好将这个变量初始化为null而不是其他的值。这样一来,只要直接检查null值就可以直接知道相应的变量是否已经保存了一个对象的引用,如下面的例子:
if(message != null){ //对message进行一系列的操作 }
实际上,undefined的值是派生自null值得,所以对它们进行相等性测试的时候要返回true:
console.log(null == undefined); //true
在这里,位于null和undefined之间的相等操作符(==)总是返回true。尽管null和undefined有这样的关系,但它们的的用途完全不同。如上面所述,无论在什么情况下,都没有必要把一个变量显示的表示为undefined,可是同样的规则对null却不适用。换句话说,只有保存对象的变量还没有真正的保存对象,就应该在明确地表示将该变量保存为null值。这样做不仅可以体现null值作为空指针的惯例,而且也有助于进一步的区分null和undefined。
Boolean类型是JavaScript中使用最多的一种类型,该类型只有两个字面值:true和false。这两个值与数字值不是一回事,因此true不一定等于1,而false也不一定等于0。以下是为变量赋值的例子:
var first = true; var second = false;
需要注意的是,boolean类型的两个值区分大小写。也就是说True和true、False和false不是一回事。
True和False(以及其他混合大小形式)只是标识符,不是boolean值。
虽然boolean值只有两个值,但是JavaScript所有类型的值都有与这两个boolean值等价的值。要将一个值转换为相应的Boolean值,可以调用Boolean()函数。例如:
var message = "Hello world!"; var messageAsBoolean = Boolean(message); console.log(messageAsBoolean); //true
可以对任何类型的值调用Boolean()函数,而且总会返回一个boolean值。至于返回的是true还是false取决于要转换的实际类型及其实际值。下表给出了各种数据类型对其转换的相应规则:
数据类型 | 转换为true的值 | 转换为false的值 |
---|---|---|
Boolean | true | false |
String | 任何非空字符串 | “”(空字符串) |
Number | 任何非零数字值(包括无穷大) | 0和NaN |
Object | 任何对象 | null |
Undefined | n/a | undefined |
在JavaScript中number类型定义了不同的数值字面量格式。例如:
var intNumber = 55; //十进制整数 var octalNum1 = 070; //八进制的56 var octaNum2 = 079; //无效的八进制数,解析为79 var octaNum3 = 08; //无效的八进制数,解析为8 var hexNum1 = 0xA; //十六进制的10 var hexNum2 = 0x1f; //十六进制的31
在进行算术计算时,所有八进制和十六进制表示的数值都会转换成十进制数值。
NaN即非数值,是一个特殊的数值。这个数用于表示一个本来要返回数值的操作数未返回数值的情况(这样就不会抛出错误了)。NaN本身有两个特点:
首先,任何涉及NaN的操作(例如NaN/10)都会返回NaN,这个特点在多步计算中有可能导致问题。
其次,NaN与任何值都不相等,包括NaN本身。例如:
console.log(NaN ==NaN ); //false
string类型用于表示零或多个Unicode字符组成的字符序列,即字符串。字符串可以由双引号(")或单引号(’)表示,因此下面两种写法都是有效的:
var firstName = "王文正"; var secondName = "王彬";
双引号开头的必须以双引号结尾,而当引号开头的必须以单引号结尾。下面这种会导致语法错误:
var name = "王彬'; //语法错误
String类型中包含了一些特殊字面量,也叫转义序列,用于表示非打印字符,或者有其他的用途的字符。这些字符字面量如下表所示:
字面量 | 含义 |
---|---|
\n | 换行 |
\t | 制表 |
\b | 退格 |
\r | 回车 |
\f | 进纸 |
\ | 斜杠 |
’ | 单引号 |
" | 双引号 |
\xnn | 以十六进制代码nn表示一个字符 |
\unnn | 以十六进制代码nnn表示一个Unicode字符 |
JavaScript中的字符串是不可变的,也就是说,字符串一旦创建,它的值就是不可更改的。要更改某个变量中保存的字符串,首先要销毁原来的字符串,然后用另一个包含新值得字符串填充变量,例如:
var lang = "java"; lang = lang + "script"; console.log(lang); //javascript
JavaScript中的对象是一组数据和功能的集合。对象可以通过执行new操作符后跟要创建的对象类型名称来创建。而创建Object类型的实例并为其添加属性或方法,就可以创建自定义对象。如下所示:
var o = new Object(); var o = new Object; //有效,但是不推荐这种做法;
constructor:保存着用于创建当期那对象的函数。
hasOwnProperty(propertyName):用于检查给定的属性在当前对象实例中(而不是实际的原型中)是否存在。
isPrototypeOf(object):用于检查传入的对象那个是否是当前对象的原型。
propertyIsEnumerable(propertyName):用于检查给定的属性是否能够使用for-in语句
toLocaleString():返回对象的字符串表示,该字符串与执行环境的地区对应
valueOf():返回对象的字符串、数值或布尔值表示。通常与toString()方法的返回值相同
toString():返回对象的字符串表示
由于在JavaScript中Object是所有对象的基础,因此所有对象都具有这些基本的属性和方法。
【相关推荐:javascript学习教程】
The above is the detailed content of Detailed analysis of the six basic data types in JavaScript. For more information, please follow other related articles on the PHP Chinese website!