Home >Web Front-end >JS Tutorial >JavaScript Advanced Programming (3rd Edition) Study Notes 3 js Simple Data Types_Basic Knowledge

JavaScript Advanced Programming (3rd Edition) Study Notes 3 js Simple Data Types_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 17:49:17934browse

ECMAScript是一种动态类型的语言,构建于5种简单数据类型(Undefined、Null、Boolean、Number、String)和一种复杂数据类型(Object)的基础之上。这篇文章就来复习一下简单数据类型,我会尽量从编程实践的角度来描述,下面代码运行环境为FireFox 14.0.1。

简单数据类型

简单数据类型 取值
Undefined undefined(只有一个值)
Null null(只有一个值)
Boolean true|false(只有两个值)
Number 数值
String 字符串

The first thing that needs to be explained is that in ECMAScript, the above five simple data types, including Boolean, Number, and String, all have built-in packaging objects with the same name, and the literal values ​​(variables) of simple data types will be automatically packaged according to the situation. , so that methods can be called directly. As for the specific methods that can be called, we will explain in detail when discussing built-in objects:

Copy code Code As follows:

console.info(true.toString());//true, which is equivalent to using Boolean() packaging and then calling
console.info(Boolean(false).toString( ));//false, convert false to Boolean type value
console.info(new Boolean(false).toString());//false, wrap false with Boolean()
console.info( false.toString());//false, which is equivalent to using Boolean() packaging and then calling
console.info('test'.toString());//test, which is equivalent to using String() packaging and then calling Call

try{
console.info(undefined.toString());//There is no corresponding packaging type and an exception is thrown
}catch(e){
console.info(e );//TypeError
}
try{
console.info(null.toString());//There is no corresponding packaging type, an exception is thrown
}catch(e){
console.info(e);//TypeError
}

var num = 4;
console.info(num.toString());//4, can be used directly on simple numerical variables Calling the method is equivalent to wrapping it with Number() and then calling
//console.info(3.toString());//SyntaxError, syntax errors cannot be captured using try, indicating that they cannot be called directly on numerical literals

Secondly, let’s talk about the most commonly used data conversions:
(1) Convert to Boolean: !!value
(2) Convert to Number: value
(3) Convert For String: '' value
The five simple data types are explained in detail below:
1. Undefined type
The Undefined data type has only one value: undefined.
(1) All uninitialized values ​​default to undefined (there is no need to explicitly initialize a variable to undefined).
(2) In the function scope, the function parameters without actual parameters passed in are undefined.
(3) When the function does not explicitly return or return;, the return value is undefined.
(4) In ECMAScript, it is stipulated that null==undefined returns true, and null===undefined returns false.
(5) The corresponding Boolean value of undefined is false.
(6) When typeof is used on undefiend, the string 'undefined' is returned. When used on a "variable" that has never been declared, it will also return 'undefined'.
(7) undefined converts the value to NaN and the string to 'undefined'.
Copy code The code is as follows:

console.info(undefined===undefined);/ /true
console.info(typeof undefined);//undefined
console.info(typeof noDefined);//undefined, undefined identifier, using typeof also returns undefined, which is also an undefined identifier The only available operator is
console.info(!undefined);//true, which returns true here, which is the basis for judging whether variables are initialized in many conditional statements.
console.info(!!undefined);/ /Any value, using double negation!! will convert it to the corresponding Boolean value. Here it is stated that the corresponding Boolean value of undefiend is false
console.info(undefined==null);//ES stipulates that null and The undefined equality test returns true
console.info(undefined===null);//But undefined and null are two data types after all. When using congruent comparison, false is returned
console.info(typeof undefined ==undefined);//false, typeof undefined returns a string 'undefined', so false is output here
console.info( undefined);//NaN, when converting the value, it is NaN
console.info ('' undefined);//undefined, converted to the string 'undefined'

2. Null type
The Null type also has only one value: null.
(1) When using typeof on a null value, the string 'object' is returned.
(2) The corresponding Boolean value of null is false.
(3) If a variable is used to save an object, it is recommended to initialize it to null.
(4) null converts the value to 0, and converts the string to 'null'.
Copy code The code is as follows:

console.info(null===null);/ /true
console.info(typeof null);//object
console.info(!null);//true
console.info(!!null);//false, indicating that null corresponds Boolean value is false
console.info(undefined==null);//true
console.info(undefined===null);//false
console.info( null);//0 , converted to the value 0
console.info('' null);//null, converted to the string 'null'

3、Boolean类型
  Boolean类型只有两个值:true和false。
(1)虽然只有两个值,但是任何一种数据类型的值都能转换为与其相对应的Boolean值,转换方式主要有三种:
  A、通过转型函数Boolean()转换
    需要注意的是,当Boolean()作为转换函数时,会转换为一个与其相应的Boolean值,当作为构造函数时,会创建一个对象,而任意非空对象的Boolean值都是true,有时候这会造成误解,建议就是不使用Boolean()。对于String()、Number()也有类似情况。
  B、通过双重否定!!操作符转换
  C、通过隐式转换,比如一些条件语句中
(2)Boolean类型的true和false,使用typeof时,均返回字符串'boolean'。
(3)在转换为数值时,true和false分别转换为1和0,转换为字符串时,分别为'true'和'false'。
复制代码 代码如下:

var value = 'test';
var empty = '';
console.info(!!value);//true
console.info(!!empty);//false
console.info(Boolean(value));//true
console.info(Boolean(empty));//false
console.info(!!value === Boolean(value));//true,说明两种转换方式等价
console.info(!!empty === Boolean(empty));//true
console.info(new Boolean(value));//Boolean对象,注意这里使用了new,会创建一个对象
console.info(new Boolean(empty));//Boolean对象
if(value){//隐式转换为true
console.info(value);//test
}
if(empty){//隐式转换为false,不执行括号内部语句
console.info('empty');
}
if(new Boolean(empty)){//先创建对象,再隐式转换为true,会执行括号内部的语句
console.info('empty');//empty
}
console.info(typeof true == 'boolean');//true
console.info(+true);//1,一元操作符,转换为数值1
console.info(+false);//0
console.info(''+true);//true,重载后的+操作符,转换为字符串'true'
console.info(''+false);//false


具体的转换规则如下:

数据类型 转换为true的值 转换为false的值
Undefined - undefined
Null - null
Boolean true false
Number 任意非0数值(包括无穷大) 0和NaN
String 任意非空字符串 空字符串
Object 任意对象 -

4. Number type

In ECMAScript, there is no separate integer or floating point type. There is only one Number type, which is represented by the IEEE754 format (this representation will have rounding errors during calculation). I will not go into the underlying implementation in detail here. These things were already a headache when I learned C language in school, and I don’t want to have another headache. Below I will put the most commonly used ones in actual programming at the front. This is generally enough. For those who don’t want to be bothered by too marginal details, you can skip the discussion about Number later at any time.

(1) Numeric conversion: mainly the following three conversion functions

  • Number() function: Similar to Boolean(), it converts data into Number type. It has the same effect as using the unary plus operator ( ). It is recommended to use the operator, which is relatively simple.
  • parseInt() function: parses integers, you can pass in data and base, for example, parseInt('070',8) outputs 56 in decimal.
  • parseFloat() function: parses floating point numbers and can only accept one parameter. It should be noted that if the result of the parsed data is an integer, it will return the integer directly.

Note: When using Number() and conversion, true—>1, false—>0, undefined—>NaN, null—>0, empty string—>0, non-empty string— >Analyze numerically.

Copy code The code is as follows:

var trueVal = true;
var falseVal = false;
var undef = undefined;
var nullVal = null;
var intVal = '1';
var floatVal = '1.0';
var strVal = 'test';
var empty = '';
console.info(Number(trueVal));//1
console.info(Number(falseVal));//0
console.info(Number( undef));//NaN
console.info(Number(nullVal));//0
console.info(Number(intVal));//1
console.info(Number(floatVal) );//1
console.info(Number(strVal));//NaN
console.info(Number(empty));//0

console.info( trueVal); //1
console.info( falseVal);//0
console.info( undef);//NaN
console.info( nullVal);//0
console.info( intVal );//1
console.info( floatVal);//1
console.info( strVal);//NaN
console.info( empty);//0

console.info(parseInt(trueVal));//NaN
console.info(parseInt(falseVal));//NaN
console.info(parseInt(undef));//NaN
console. info(parseInt(nullVal));//NaN
console.info(parseInt(intVal));//1
console.info(parseInt(floatVal));//1
console.info( parseInt(strVal));//NaN
console.info(parseInt(empty));//NaN

console.info(parseFloat(trueVal));//NaN
console.info (parseFloat(falseVal));//NaN
console.info(parseFloat(undef));//NaN
console.info(parseFloat(nullVal));//NaN
console.info(parseFloat (intVal));//1
console.info(parseFloat(floatVal));//1
console.info(parseFloat(strVal));//NaN
console.info(parseFloat(empty ));//NaN

Note: The behavior of these conversion functions may differ due to different implementations of browsers. It is recommended that you write your own tests if you have any questions during the actual programming process. In "Advanced Programming with JavaScript (3rd Edition)", there are many places described in this section that are different from my actual running results. For example, the original book says that parseInt() can only parse strings, but the following code can also be run. :
Copy code The code is as follows:

var object = {
value:1,
toString:function(){
return this.value;
}
};
console.info(parseInt(object));//1

(2) Integers and floating-point numbers: People who are influenced by C language must stubbornly distinguish between integers and floating-point numbers! In ECMAScript, they are not as different as expected. To put it simply, a value that contains a decimal point and has at least one digit after the decimal point that is not 0 is a floating point number, otherwise it is an integer. For example, 1.01 is a floating point number, and 1., 1.00 because there is no non-zero after the decimal point. A number of 0 will be parsed by the engine into an integer 1. You may imagine that the result of dividing two integers will also be rounded, such as 3 / 2 = 1, but in ECMAScript, don’t worry about this, its mathematical properties have been restored, and you will find that 3 / 2 = 1.5, this One point will be mentioned again in the operator-related section.

(3) Base system: also called the carry system, it is actually the method of carrying (lower bit to higher bit). Each base system has a base. When the low-digit value reaches this base, it carries to the high-digit value. 1. In daily life, the most commonly used system is the decimal system. For example, 10 cents is rounded up to 1 yuan. In time measurement, there are also the 24-based system (24 hours is one day) and the hexadecimal system (60 seconds is one day). points), in ancient times, hexadecimal was also used (think about half a pound). However, in computer processing, since the current only has two states: on and off, it can only process binary data. However, this is difficult for natural people to understand, so octal and hexadecimal are used as decimal systems. and the intermediate state of binary conversion.

In ES3, you can use octal, decimal, and hexadecimal, but in ES5, octal has been disabled.

Octal: Starting with a digit of 0, followed by a sequence of octal numbers (0~7). If the number exceeds 7, the leading 0 will be ignored and treated as a decimal. For example, 08 will Parsed as the decimal number 8.

Hexadecimal: It starts with a digit of 0 and a letter x, followed by a sequence of hexadecimal numbers (0-9a-fA-F).

Decimal system: You can write all the digits directly one by one, or you can use scientific notation (don’t understand? Find a middle school mathematics textbook and take a look).

(3) Special values: In ECMAScript, there are two special values ​​NaN and Infinity that you need to pay attention to. The former means not a number (Not a Number), and the latter means a value that is not within the representation range. You can also use positive and negative signs to indicate direction. For these two special values, we will not examine the specific operation rules here (if you are interested, you can test it yourself, and I will also give some examples below). I will only make the following two explanations:

A. You cannot use val==NaN to determine whether a variable is NaN, but use the global isNaN() function. This function accepts a parameter and returns true when the parameter can be converted to a numerical value, otherwise it returns false.

B. Try not to use val==Infinity to determine whether it is out of range, but use the global isFinite() function. This function accepts a parameter and returns true when the parameter value is within the range, otherwise it returns false. The representation range mentioned here refers to from Number.MIN_VALUE to Number.MAX_VALUE. In addition, in Number, there are attributes Number.NEGATIVE_INFINITY and Number.POSITIVE_INFINITY, whose values ​​are Infinity and -Infinity respectively.
Copy code The code is as follows:

console.info(0/0); //NaN
console.info(NaN==NaN);//false
console.info(NaN 1);//NaN
console.info(NaN/NaN);//NaN

var notNumber = NaN;
console.info(notNumber==NaN);//false
console.info(isNaN(notNumber));//true
console.info(1/0); //Infinity
console.info(-1/0); //-Infinity
console.info(1/Infinity);//0
console.info(Infinity/Infinity);//NaN
console.info(Infinity==Infinity); //true
var inf = Infinity;
console.info(inf==Infinity); //true
console.info(!isFinite( inf));//true
console.info(!isFinite(NaN));//true
console.info(isNaN(Infinity));//false

Note : On page 29 of "Advanced Programming with JavaScript (3rd Edition)", it is said that any value divided by 0 will return NaN. This is not actually the case.

5. String type

Unlike general C-like languages, in ECMAScript, there is no character type, and the string type String is used as a simple type, and its literal uses quotation marks (single Quotes ' or double quotes ").

(1) For string type operations, the plus sign " " is overloaded. If any value is added to a string, it will first be added using String( ) into a string, and then merge the two strings (2) Use String() to convert, undefined—>'undefined', null—>'null', true—>' true', false—>'false', numerical type Number—> Convert by numerically visible characters, object Object—> call toString


Copy code<.> The code is as follows: console.info('' 1 1);//11, not 2
console.info('' true);/ /true
console.info('' undefined);//undefined
console.info('' null);//null

(3) Strings are escaped using backslash "". Some common escape characters are:

字面量 含义 字面量 含义
n 换行 \ 反斜杠
t 制表 ' 单引号
b 空格 " 双引号
r 回车 xnn 以十六进制代码nn表示的一个字符
f 进纸 unnnn 以十六进制代码nnnn表示的一个Unicode字符

Okay, that’s all about simple data types.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn