Study notes 3—JavaScript data types

1 Data type

ECMAScript has 6 simple data types (also known as primitive types): Undefined, Null, Boolean, Number, String, and Symbol. Symbol (symbol) is new in ECMAScript6. There is also a complex data type called Object.

1.1 typeof operator

Because the type of ECMAScript is loose, a means is needed to determine the data type of any variable. Using the typeof operator on a value will return one of the following strings:
"undefined" means the value is undefined,
"boolean" means the value is a Boolean value,
"string" means the value is a string,
"number" means the value is a value,
"object" means a value Is an object or null
"function" means the value is a function
"symbol" means the value is a symbol

        let message = "some string"; 
        console.log(typeof message); //"string"
        console.log(typeof(message)); //"string"
        console.log(typeof 95); //"number"

Because typeof is an operator and not a function, no parameters are needed, but parameters can be used. Note that the result returned by typeof in some cases may be confusing, but it is technically correct. For example, calling typeof null returns "object". This is because the special value null is considered a reference to an empty object. The value returned by typeof is a string:

        let message;
        console.log(typeof typeof message); //string

Strictly speaking, functions are considered objects in ECMAScript and do not represent a data type. But functions also have their own special attributes, so it is necessary to distinguish functions from other objects through the typeof operator.

1.2 Undefined type

The Undefined type has only one value, which is the special value undefined. When a variable is declared with var or let but not initialized, it is equivalent to assigning an undefined value to the variable.

        let message;
        console.log(message == undefined); //true

It did not exist before ECMA-262 version 3. The purpose of adding this special value is to clarify the difference between a null object pointer and an uninitialized variable.
Note that there is a difference between a variable containing an undefined value and an undefined variable:

        let message;
        console.log(message); //undefined
        console.log(age); //undefined
        
        console.log(message); //undefined
        console.log(age); //报错

Whether declared or undeclared, typeof returns the string undefined. We recommend that you initialize the variable while declaring it, so that when typeof returns undefined, you will know that it is undeclared rather than declared but not initialized. undefined is a false value:

        let message; //声明但未初始化
        //age未声明

        if (message) {
    
    
            //这个块不会执行
        }

        if (!message) {
    
    
            //这个块会执行
        }

        if (age) {
    
    
            //报错
        }

1.3 Null type

The Null type also has only one value, the special value null. Logically speaking, the null value represents a null object pointer, which is why passing a null to typeof will return "object":

        let car = null;
        console.log(typeof car);//object

When defining a variable that will save the object value in the future, it is recommended to initialize it with null instead of other values. In this way, as long as you check whether the value of this variable is null, you can know whether this variable was later assigned a reference to an object, such as:

if(car != null){
    
    
	//car是一个对象的引用
}

The undefined value is derived from the null value, so ECMA-262 defines them as ostensibly equal, such as:

console.log(null == undefined);//true

null is a false value:

        let car = null;
        if(car){
    
    
            //这个块不会执行
        }

        if(!car){
    
    
            //这个块会执行
        }

1.4 Boolean type

The Boolean type has two literal values: true and false. These two Boolean values ​​are different from numeric values, so true is not equal to 1, and false is not equal to 0. Note that the Boolean literals true and false are case-sensitive, so True and False are valid identifiers rather than Boolean values.
Although there are only two Boolean values, all other ECMAScript values ​​have equivalent forms of corresponding Boolean values. To convert a value of another type to a Boolean value, you can call the specific Boolean() conversion function:

        let message = "Hello world";
        let messageAsBoolean = Boolean(message);

In this example, the string message will be converted to a Boolean value and stored in the variable messageAsBoolean. The Boolean() transformation function can be called on any type of data and always returns a Boolean value. The following table summarizes the conversion rules between different types and Boolean values:

type of data Value converted to true Value converted to false
Boolean true false
String Non-empty string "" Empty string
Number Non-zero value 0 、 NaN
Object Any object null
Undefined N/A (not exist) undefined

It is very important to understand the above conversion, because flow control statements such as if will automatically perform the conversion of other types of values ​​to Boolean values, for example:

        let message = "Hello world!";
        if (message){
    
    
            console.log("Value is true");
        }

In this example, console.log will output the string Value is true, because the string message will be automatically converted to the equivalent Boolean value true.

1.5 Number type

Integers can also be represented by octal or hexadecimal literals. For octal literals, the first digit must be 0, and then the corresponding octal digit. If the number contained in the literal exceeds the expected range, the prefix 0 will be ignored, and the following sequence of numbers will be treated as a decimal number , as follows:

        let octalNum1 = 070; //8进制的56
        let octalNum2 = 079; //无效的8进制,当成79处理
        let octalNum3 = 08; //无效的8进制,当成8处理

To create a hex literal, must let the real value of the prefix 0x ( case-sensitive ), followed by 16 hexadecimal digits (0 to 9 and 0 ~ F), hexadecimal digits in uppercase or lowercase letters :

        let hexNum1 = 0xA; //16进制的10
        let hexNum2 = 0x1f; //16进制的31

(1) Floating point value
To define a floating point value, the value must include a decimal point, and there must be at least one digit after the decimal point. Although it is not necessary to have an integer before the decimal point, it is recommended to add:

        let floatNum1 = 1.1;
        let floatNum2 = 0.1;
        let floatNum3 = .1;

Because the memory space used to store floating-point values ​​is twice that of storing integer values, ECMAScript always finds ways to convert values ​​to integers. When there is no number after the decimal point, the value will become an integer. If the value itself is an integer, but the decimal point is followed by 0, it will also be converted to integer
scientific notation: The format requirement of scientific notation in ECMAScript is a The value (integer or floating point) is followed by an uppercase or lowercase letter e, plus a power of 10 to be multiplied by:

let floatNum = 3.125e7;

The accuracy of floating-point values ​​can reach up to 17 decimal places, but in arithmetic calculations, it is far less accurate than integers. For example, 0.1+0.2 gets 0.30000000000000004 instead of 0.3. Due to this slight rounding error, it is difficult to test specific floats. Point value:

        let a = 0.3,
            b = 0.1;
        if (a + b == 0.3) {
    
    
            console.log("You got 0.3");
        }

(2) The range of values ​​The
minimum value that ECMAScript can represent is stored in Number.MIN_VALUE, which is 5e-324 in most browsers; the maximum value that can be represented is stored in Number.MAX_VALUE, which is in most browsers It is 1.7976931348623157e+308. If the result of a calculated value exceeds the range that JavaScript can represent, then this value will be automatically converted to a special Infinity value. Any negative number that cannot be represented is represented by -Infinity (negative infinity), and any positive number that cannot be represented is represented by Infinity (positive infinity).
To determine whether a value is finite, you can use the isFinite() function.
(3) NaN
has a special value called NaN, which means not a number (Not a Number), which is used to indicate that the operation to return a value has failed. For example, dividing any value by 0 will usually cause an error in other languages, thus aborting code execution. But in ECMAScript dividing by 0, +0, or -0 will return NaN:

        console.log(1 / 0); //Infinity
        console.log(-1 / 0); //-Infinity
        console.log(-0 / 0); //NaN

Unique properties of NaN: Any operation involving NaN always returns NaN, and secondly, NaN is not equal to any value including NaN.

        console.log(NaN == NaN); //false;

To this end, ECMAScript provides the isNaN() function. This function accepts a parameter, which can be any data type, and then judges whether this parameter is "not a numeric value". After passing a value to isNaN(), the function will try to convert it to a number. Certain non-numeric values ​​can be directly converted to numeric values, and any value that cannot be converted to numeric values ​​will cause this function to return true :

        console.log(isNaN(NaN));//true
        console.log(isNaN(10));//false
        console.log(isNaN("10"));//false
        console.log(isNaN("blue")); //true
        console.log(isNaN(true));//false

(4) Numerical conversion
There are 3 functions to convert non-numerical values ​​to numerical values: Number(), parseInt() and parseFloat(). Number() is a transformation function and can be used for any data type. The latter two functions are mainly used to convert character strings to numeric values. For the same parameter, these three functions perform different operations.
The Number() function performs the conversion based on the following rules:
Boolean value, true is converted to 1, false is converted to 0.
Numerical value, directly returned.
null, return 0.
undefined, return NaN
string, apply the following rules:

  • If the string contains numeric characters, including plus and minus signs in front of the numeric characters, it is converted to a decimal value. Therefore, Number ("1") returns 1, Number ("123") returns 123, Number ("011") returns 11 (ignoring the preceding 0);
  • If the string contains a valid floating-point value format such as "1.1", it will be converted to the corresponding floating-point value (the preceding 0 will also be ignored).
  • If the string contains a valid hexadecimal format such as "0xf", it will be converted to a decimal integer value corresponding to the hexadecimal.
  • If it is an empty string, return 0
  • If the string contains characters other than the above, NaN is returned.

Object, call the valueOf() method, and convert the returned value according to the above rules. If the conversion result is NaN, call the toString() method, and then convert according to the rules for converting strings.

        let num1 = Number("Hello world"); //NaN
        let num2 = Number(""); //0
        let num3 = Number("000011"); //11
        let num4 = Number(true); //1

parseInt():
Considering that the Number() function is relatively complicated and a bit unconventional when converting a string, usually when you need to get an integer, you can use the parseInt() function first. The parseInt() function is more focused on whether the string contains a numeric pattern. The leading space of the string will be ignored, and the conversion will start from the first non-space string. If the first string is not a numeric character, plus or minus sign, parseInt() immediately returns NaN. This means that an empty string will also return NaN (this is not the same as Number(), which returns 0). If the first character is a numeric character, a plus sign, or a minus sign, each character is continuously detected in turn until the end of the string or a non-numeric character is encountered. For example, "1234blue" will be converted to 1234, because blue will be completely ignored. Similarly, "22.5" will be converted to 22 because the decimal point is not a valid integer character.
The parseInt() function can also recognize different integer formats (decimal, octal, hexadecimal). If the string starts with "0x", it will be interpreted as hexadecimal. If the string starts with "0" and is followed by a numeric character, it will be interpreted as an octal integer by some implementations in non-strict mode :

        let num1 = parseInt("1234blue");//1234
        let num2 = parseInt("");//NaN
        let num3 = parseInt("0xA"); //10
        let num4 = parseInt(22.5); //22
        let num5 = parseInt("70"); //70
        let num6 = parseInt("0xf");//15

Different numeric formats are easy to confuse, so parseInt() also accepts a second parameter to specify the base. If you know that the value to be parsed is hexadecimal, you can pass in 16 as the second parameter for correct analysis:

let num = parseInt("0xAF",16);

In fact, if a hexadecimal parameter is provided, the 0x before the string can be omitted.
parseFloat(): The
parseFloat() function works in a similar way to the parseInt() function, and each character is detected from position 0. Similarly, it is parsed to the end of the string or to an invalid floating-point numeric character. This means that the decimal point in the first occurrence is valid, but the decimal point in the second occurrence is invalid, and the remaining characters of the string will be ignored.
Another difference of the parseFloat() function is that it always ignores the 0 at the beginning of the string. This function can recognize all the floating point formats discussed earlier, as well as the decimal format (the beginning 0 is always ignored). Hexadecimal values ​​will always return 0. Therefore parseFloat() only parses decimal values, so the base cannot be specified.

        let num1 = parseFloat("1234blue");//1234
        let num2 = parseFloat("0xA");//0
        let num3 = parseFloat(22.5); //22.5
        let num4 = parseFloat("22.34.5"); //22.34
        let num5 = parseFloat("0908.5"); //908.5
        let num6 = parseFloat("3.125e7");//31250000

1.6 String type

Strings can be identified by double quotes ("), but quotes (') or backticks (`), so the following codes are all legal:

        let firstName = "John";
        let lastName = 'Jacob';
        let lastName = `Jingleheimerschmidt`;

In ECMAScript syntax, there is no difference in string quotes.
(1) Character literal The
string data type contains some character literals, which are used to represent non-printing characters or characters for other purposes:

Literal meaning
\n Wrap
\t tabulation
\b backspace
\r Carriage return
\f Change page
\ Backslash()
apostrophe
" Double quotes
` Backticks
\ xnn The character represented by hexadecimal code nn (where) n is a hexadecimal number 0~F, for example \x41 is equal to "A"
\ unnn The Unicode character represented by hexadecimal code nnnn (where n is the hexadecimal digit 0~F), for example, \u03a3 is equal to the Greek letter " Σ \SigmaΣ
        let firstName = "John";
        console.log(firstName.length);

The escape sequence represents a character, and the length of the string can be obtained through its length property.
(2) The characteristics of strings The strings in
ECMAScript are immutable, which means that once they are created, their values ​​cannot be changed. To modify the string value in a variable, you must first destroy the original string, and then save another string containing the new value to the variable.
(3) Convert to string
There are two ways to convert a value to string. The first is to use the toString() method that almost all values ​​have. The only purpose of this method is to return the string equivalent of the current value:

        let age = 11;
        let ageAsString = age.toString();
        let found = true;
        let foundAsString = found.toString();

The toString() method can be found in numeric, boolean, object, and string values. There is no toString() method for null and undefined values.
If you are not sure whether a value is null or undefined, you can use the String() transformation function, which will always return a string representing the value of the corresponding type.

        let value1 = 10;
        let value2 = true;
        let value3 = null;
        let value4;

        console.log(String(value1));
        console.log(String(value2));
        console.log(String(value3));
        console.log(String(value4));

(4) Template literals
ECMAScript6 has added the ability to use template literals to define strings. Unlike using single or double quotes, template literals retain newline characters, and you can define strings across lines:

        let value1 = 'first line\nsecond line'
        let value2 = `first line
second line`;
        console.log(value1);
        //first line
        //second line

        console.log(value2);
        //first line
        //second line

As the name suggests, template literals are particularly useful when defining templates, such as the following HTML template:

        let pageHTML = `
        <div>
            <a href = "#">
                <span>Jake</span>
            </a>
        </div>
        `;

Because the template literal will keep the spaces inside the backtick, you must pay special attention when using it. A properly formatted template string may look improperly indented.
(5) String interpolation
One of the most commonly used features of template literals is to support string interpolation, that is, one or more values ​​can be inserted in a continuous definition. Technically speaking, the template literal is not a string, but a special JavaScript syntax expression, but the evaluation is a string. Template literals are evaluated immediately when they are defined and converted to string instances, and any inserted variables will also take values ​​from their nearest scope.
String interpolation is achieved by using a JavaScript expression in ${}:

        let value = 5;
        let exponent = 'second';
        //以前,字符串插值是这样实现的
        let interpolatedString = value + ' to the ' + exponent + ' power is ' + (value * value);

        //现在可以用模板字面量这样实现:
        let interpolatedTemplateLiteral = `${
      
      value} to the ${
      
      exponent} power is ${
      
      value*value}`;

        console.log(interpolatedString);
        console.log(interpolatedTemplateLiteral);

All inserted values ​​will be cast to a string using toString(), and any JavaScript expression can be used for interpolation. Functions and methods can be called in interpolation expressions:

        function capitalize(word) {
    
    
            return `${
      
      word[0].toUpperCase()}${
      
      word.slice(1)}`;
        }
        console.log(`${
      
      capitalize('hello')},${
      
      capitalize('world')}!`);

Guess you like

Origin blog.csdn.net/qq_43599049/article/details/112790814