1, Number type:

  • Positive/negative/zero/decimal
  • Infinity is the value of Infinity, and -infinity is the value of negative Infinity
  • NaN(not a number) is not a significant number, but it is of type Number
var num = 10-'A'; //NaN NaN == NaN; //false NaN is not equal to NaN itself.Copy the code
IsNaN ([value]) : Checks whether a value [value] is an “insignificant” digit, returning true if it is not, and false otherwise.
  • When using isNaN detection, if [value] is a non-numeric value, the browser will convert [value] to a numeric value by default before detecting it again. “Implicit conversion” : the browser will handle this privately by default.

  • In “implicit conversions,” the browser converts data types based on Number([value]).

// Requirement: Verify that a value is a valid number? /* if(num==NaN){alert('num is not a valid number! '); } */ // If (isNaN(num)){alert('num 'is not a valid number! ')}Copy the code
Convert other data types to number
  • Number([value])This is how isNaN converts to numbers. Number is a built-in JS conversion method that can “force” other data types to a Number.
    • String to number: Empty strings are converted to 0, and if any non-significant numeric character is present in the string, the result is converted to NaN.
    • Boolean converts to numbers: true->1, false->0.
    • Null – > 0, undefined – > NaN.
    • Symbol value Cannot be converted to a number (Uncaught TypeError:Cannot convert a symbol value to a number)
    • Bigint can be converted to a number.
    • Convert a reference data type (object or function) to a number.
      1. First get the value of its [Symbol. ToPrimitive] attribute.
      2. If there is no [Symbol. ToPrimitive] attribute, then get its valueOf value (the original value).
      3. If there is still no valueOf value (the original value), it is finally converted to the string toString() and then to the Number().
      • Convert objects to numbers: Convert objects to strings and then strings to numbers.
        • Ordinary objects
        • The array object
        • The rest of the object format is basically a numeric NaN.
      • Function is converted to a number, and the result is NaN.

console.log(Number('12')); / / = > 12 console. The log (Number (' 12.5 ')); / / = > 12.5 the console. The log (Number (' 12 px)); / / = > NaN console. The log (Number (' 12.5.0 ')); //=>NaN console.log(Number(true)); //=>1 console.log(Number(false)); //=>0 console.log(Number(null)); //=>0 console.log(Number(undefined)); //=>NaN console.log(Number(symbol(13))); Console. log(Number(function func(){})); 1. Convert obj to string "[object object]" //2. ("[object object]") let obj = {x:100} console.log(Number(obj)); =>NaN //1. Convert arr to string "10" //2. Let arr = ["10"] console.log(Number(arr)); 1. Convert arr to the string "10,20" //2. NaN arr=["10","20"]; NaN arr=["10","20"]; console.log(Number(arr)); =>NaN console.log(isNaN('AA')); / / = > true on the console. The log (isNaN (' 12.5 ')); / / = > false console. The log (isNaN (' 12.5 px)); //=>true console.log(isNaN([])); //=>false console.log(isNaN([10])); / / = > false console. The log (isNaN ([10, 20])); //=>true console.log(isNaN({})); //=>true console.log(isNaN(null)); //=>false console.log(isNaN(undefined)); //=>true console.log(isNaN(Symbol(1))); / / an errorCopy the code
  • parseInt([value])/parseFloat([value])
    • Make sure [value] is a string. If not, first “implicitly” convert it to the string [value].toString().
    • The search starts from the first character on the left of the string, turns the valid numeric character to the right, and finally converts it to a number. (The search stops when a non-valid numeric character is encountered, and the search stops regardless of whether there are any more valid numeric characters after it.)
    • If no valid numeric character is found, the result is still NaN.
    • ParseFloat recognizes one more decimal point than parseInt.

<script> console.log(Number('12px')); //=>NaN console.log(parseInt('12px')); //=>12 console.log(parseInt('12px24')); //=>12 console.log(parseInt('width:12px')); / / = > NaN console. The log (parseInt (' 12.5 px)); / / = > 12 console. The log (parseFloat (' 12.5 px)); Console. log(Number(true)); //=>12.5 parseFloat identifies more decimal points than parseInt console.log(Number(true)); //=>1 console.log(parseInt(true)); //=> convert true to string "true" parseInt('true') =>NaN console.log(parseInt(NaN)); //=>NaN console.log(Number(null)); //=>0 console.log(parseInt(null)); / / = > parseInt (' null ') = > NaN. The console log (isNaN (Number (parseInt (" 0.8 ")))); / / = > parseInt (" 0.8 ") - > 0 Number (0) - > 0 isNaN (0) - > false console. The log (Number (")); //=>0 console.log(parseInt('')); //=>NaN </script>Copy the code

The result is:

[number value]. ToFixed ([N]): retain N digits behind the decimal point.

<script> //toFixed(N) : keep N digits behind the decimal point (the final result is a string) let N = 3.1415926; console.log(n.toFixed(2)); / / = > "3.14" is the console. The log (Number. MAX_SAFE_INTEGER); Console. log(9007199254740992 == 9007199254740993); //=> 9007199254740992; //ES6 provides a new data type BigInt: Log (BigInt(9007199254740992), BigInt(9007199254740993)); </script>Copy the code

The result is:

The data type is string

  1. In JS, single quotes ”/ double quotes “”/ backquotes ” are all strings.
  2. A string is composed of zero to more characters, each character has its own positional “index”, and there is a length to store the length of the string.
  3. Each character in a string has an “index “(number) that represents its position.
    • You start at 0 and you work your way up.
    • Index 0: the first character, index 1: the second character.
    • STR [index] Gets the character at the specified index position.
var str = "xiaoyunduo2021"; console.log(str.length); //=>14 console.log(str[0]); //=>'x' console.log(str[str.length-1]); / / = > '1'Copy the code
  1. Strings have a number of methods that they can call: – chartAt – charCodeAt – substr – substring – slice – split – replace – indexOf/lastIndexOf – includes – trim – match – .

/ / STR. Substr (n, m) : starting from the index n intercept "m" characters, / / STR. The substring (n, m) : starting from the index n find "index m" (excluding m), the interception of index n and index m (excluding m) between the characters / / m not writing are intercepted by the end of the string, don't support the negative index, Var STR = "xiaoyunduo"; var STR = "xiaoyunduo"; The console. The log (STR. Substr (2, 4)); / / "aoyu" console. The log (STR) the substring (2, 4)); //"ao"Copy the code
  1. Converts other data types to string types
    • String([value])
    • [value].toString()
    • String concatenation
    • Before converting an object to a number, convert it to a string
    • Alert/confirm/prompt, etc.
    • .
  • Features:
    • Basically, you can wrap it in double or single quotes.
    • No matter what information the object contains, it is converted to “[object object]”.
    • Converting an array object to a string is “first item, second item…” (each item in the array is separated by a comma), [] is converted to an empty string.
  1. In JS commonly used mathematical operations
  • Mathematical operations: + – * / addition, subtraction, multiplication and division

  • Take the remainder of % (membrane)

  • Except for addition, all cases are mathematical (if you encounter a non-numeric type, you need to cast it to a numeric type based on Number and then perform the operation);

  • Plus in JS both mathematical operations, also has the meaning of string concatenation (as long as the plus on both sides of any side of the string, it becomes string concatenation);

    “+” + string concatenation

    • On either side of the plus sign, a string appears, and the result is string concatenation.
    • On the left and right sides of the plus sign, an object appears (to convert an object into a number and perform mathematical operations).
      • First get the [Symbol. ToPrimitive]/valueOf of the object.

      • If none of the above gets the original value, the object is converted to a string based on toString.

      • And then you have a problem, “There’s a string on either side of the plus sign,” and then you’re not doing math anymore, you’re concatenating strings.

      • The plus sign appears on one side, so that this side is a mathematical operation even if it is a string/object.

      • If it is a “{}” plus content, the “{}” does not participate in the operation, just relative to a block of code.

The console. The log (10 + [10, 20]); / / = > [10, 20] [] [Symbol. ToPrimitive] undefined / / = > [10, 20]. The valueOf () [10, 20] is not original value / / = > 10 + 10, 20 "at this time this is the string concatenation = >" 1010" console.log(10+new Number(10)); //=>new Number(10)[Symbol. ToPrimitive] undefined //=>new Number(10).valueof () 10 //=> 10+10 => 20 var s = "10"; console.log(+s); //=>10 console.log(+[10]); //=>10 console.log(s++); //=>10 console.log(s); //=>11 console.log(3 - "3px"); //=>NaN console.log(3 + "3px"); //=>"33px" string concatenation console.log(1 + "1"); //=>"11" string concatenation console.log(1 + {}); Console.log (1 + []); //=>"1[object object]"; console.log(1 + []); //=>'1'; '1'.console. log([10] + true); //=>"10 "; //=>"10 "; //=>"10 "; //=>"true10" console.log(1 + true); //=>2 */ console.log(4 / 2); //=> divide by 2 console.log(7/3); //=> except 2.3333333333333335 console.log(7%3); //=> mod 1 console.log(10 - null); //=>10 console.log(3 * undefined); //=>NaN console.log(true - "12"); //=>1-12 =>-11 console.log(100 + true + 21.2 + null + undefined + "Tencent" + [] + null + 9 + false); /* 100 + true => 101 101 + 21.2 => 122.2 122.2 + null => 122.2 122.2 + undefined => NaN NaN + "Tencent" => "NaNTencent" "NaNTencent" + [] => "NaNTencent" + null => "NaNTencentnull" "NaNTencentnull" + 9 => "NaNTencentnull9" "NaNTencentnull9" + false => "NaNTencentnull9false" */Copy the code

Boolean data types and other basic data types

Boolean data type: true/flase

  • How do I convert another data type to a Boolean

    • Boolean([value])
    • !!!!! [value] invert, invert, invert, invert, invert
    • Rule: Only “0/NaN/ NULL /undefined/ empty string” results in false, the rest is true

    ! [value] Converts the specified value to a Boolean type and inverts it

console.log(!! 1); //=>true console.log(! 1); //=>false console.log(!! - 1); //=>true console.log(!! 0); //=>false console.log(!! undefined); //=>false console.log(!! Number('12px')); //=>Number('12px')->NaN false console.log(!! []); //=>true console.log(!! "); //=>false console.log(!! {}); */ if (1) {} //=> write a value to convert it to a Boolean, Then check procedure of true and false if (3 + '3 p') {} / / = > 3 + '3 p' = > '33 px' true true if (3 - '3 p') {} / / = > 3 - '3 px = > NaN false false if (10) {} // We will first convert 10 to a Boolean type and then verify that the condition is true or falseCopy the code

2, symbol unique value data type

console.log(Symbol() == Symbol()); //false creates two unique values var n = Symbol(); console.log(n==n); Console. log(Symbol('AA') == Symbol('AA')); False = false; false = falseCopy the code

BigInt Specifies the data type of a large number

BigInt: a large number type followed by an n

  • Real scenario: When data is obtained from the server and stored on the server, if the number used for storing data exceeds the maximum security number, the information returned to the client may exceed the maximum security number, resulting in inaccurate subsequent calculations.
Number.MAX_SAFE_INTEGER; // The maximum safe Number is 9007199254740991 (16 bits) number. MIN_SAFE_INTEGER; // The minimum safe number is 9007199254740991 // the maximum safe number is exceeded, and the result is inaccurate console.log(9007199254740991+2); //9007199254740992 console.log(9007199254740992+3); //9007199254740996 BigInt("9007199254740992"); //=>9007199254740992nCopy the code

Object data types

Object data type

  • Ordinary objects {} “class arrays, instances, prototype objects…”

  • Array object []

  • Regular object /^$/

  • The date object

  • Set/Map

  • .

Ordinary objects

1. An object is composed of zero to multiple groups of “key-value pairs” (attribute name: attribute value)

  • The property name (key) is not a variable; it is a property (feature) of the object
  • The property name is usually a string (it can also be a number or a value of a basic type such as Symbol)
  • The property name cannot be an object or a function. If an object or function is the property name, the browser will convert it to a string
var x = { xx: 'xxx' }; Var y = {/ / the name is called the property name, here is a string "name" / / "clouds" is the attribute value of the current name attribute name: "clouds", the age: 11, 0: 100, // For Symbol type attribute names, wrap them based on [] to ensure syntax correctness [Symbol('AA')]: {xx:' XXX '}). ToString () => "[object object]" [{xx:' XXX '}]:300, // x->"x" It is a string x x: 300}; console.log(y); let n = { x: 100 }; let m = [100, 200]; let obj = {}; Obj [n] = 1; / / = > obj [{x: 100}] but object cannot serve as the property name, need to convert it to a string = > {" [object object] ":" clouds "} obj [m] = "clouds"; / / = > obj = > [[100200]] {" 100200 ", "cloud"} the console. The log (obj);Copy the code

2. Obtain the property value corresponding to a property name of an object, also known as Object member Access.

Attribute name: This method does not apply to attribute names of "number or Symbol type", in which case only the attribute name can be accessed based on the object. "Obj [name] and obj["name"] are not the same case".Copy the code
let obj = { sex: 0 }; // 1. Obtain the attribute value of the specified attribute name. console.log(obj.sex); //=>0 console.log(obj['sex']); Log (obj['age']) console.log(obj['age']); Console.log (object.keys (obj)); //=>undefined // 3. // =>["sex"] var obj = {name: 'cloud ', 0: 100}; console.log(obj.name); //' cloud 'console.log(obj["name"]); //' cloud 'console.log(obj[0]); //100 console.log(obj.0); //Uncaught SyntaxError: missing ) after argument list console.log(obj.age); Console.log (age); // Use undefined console.log(age); // Use undefined console.log(age); // Use undefined console.log(age); // Uncaught ReferenceError: Age is not definedCopy the code

Obj [‘x’] obj[‘x’

  • Value of type ‘x’.

  • X it’s not a value, it’s a variable that represents the value 10 stored in the variable x.

  • Obj [value] is directly a member access to the object.

  • Obj [variable] first obtains the value of the variable x, then uses the value stored in the variable x as the property name, and then accesses the members of the object.

ar x = 10; Var obj = {x: cloud, 10: 100}; console.log(obj.x); / / access the object attribute name is "x" the corresponding attribute value - > "clouds" is the console. The log (obj [' x ']); ->" cloud "console.log(obj[x]); => obj[10] ->100 let n = 100; let obj = { 1: 100 }; console.log(obj[1]); console.log(obj.1); //=>Uncaught SyntaxError: missing) After argument list Log (obj[1]); console.log(obj['1']); Obj. N = 200; obj. N = 200; //=> {n:200} obj['n'] = 200; //=> {n:200} obj[n] = 200; //=> {100:200} => obj[m] =200; //=> {100:200} => obj[m] =200; //=>Uncaught ReferenceError: m is not defined obj[true] = 300; //=>{true:300} obj[undefined] = 400; //=>{undefined:400}Copy the code

3. Manage members of an object

  • (For Symbol or object type attribute names, as well as values that need to be stored in a variable as attribute names, they need to be wrapped in brackets [] for syntax correctness.)

  • Dynamic management of members based on JS (add/modify/delete)

  • The members of an object are not allowed to be repeated (0 and ‘0’ are treated as the same member). In dynamic control, having a member before is a change in the value of the member’s property. Without a member, a new member is added to the object.

var symb = Symbol('xx'); Var obj = {name: 'cloud ', 0:10, // symb:' XXX ', var obj = {name: 'cloud ', 0:10, // symb:' XXX ', // // The attribute name is Symbol(xx), equivalent to the value stored in the variable as the attribute name}; console.log(obj[symb]); //=>'xxx' var symb = Symbol('xx'); Var obj = {name: 'cloud ', 0: 10}; obj.age = 11; Obj ["age"] = 11; Obj ["symb"] = 'XXX '; Obj [symb] = 'XXX '; / / - > obj [Symbol (xx)] = 'XXX' is equivalent to obj increase Symbol (' xx ') : 'XXX' this attribute obj [' name '] = "clouds"; Console. log(obj[0]); //=>10 console.log(obj["0"]); //=>10 // select * from 'undefined' where 'undefined' = 'undefined' where 'undefined' = 'undefined' where 'undefined' = 'undefined'; Obj. Name = undefined; Delete obj["name"]; console.log(obj);Copy the code

Special object

Special objects: arrays or array-like objects (collections).

  • The attribute name (member/key) is a number, and the number starts at zero and increases successively,

    • The sequential and regular number attribute names are called “indexes” : those that record the location of each item.
    • The first index is 0, the second index is 1… The last index is length-1.
  • There is a length member that stores the length of the collection.

    Array/array-like [index] for member access and related operations.

Var arr = [10, 20, 30]; var arr = [10, 20, 30]; console.log(arr[0]); Console. log(arr[arr.length-1]); // Get the value of the last item console.log(arr); Var obj = {0: 10, 1: 20, 2: 30, length: 3}; console.log(obj); / / HTMLCollection set: the console class array. The log (document. GetElementsByTagName (' * ')); / / the NodeList node set: the console class array. The log (document. QuerySelectorAll (' * '));Copy the code

5. The data type of function

Function: is a method that implements a function.

Why is he in a relationship?

  • We store attributes or methods (features) that describe the current thing together to prevent overwriting or conflicting variables
        var person1={
          name:'xxx',
          age:25
        };
Copy the code

Why is there a function?

  • A function is simply a method/function

  • Encapsulation: Encapsulate the code that implements the current function into the function. If you want to implement this function in the later period, you can directly call the function to execute it without rewriting the code, which improves the development efficiency and reduces the redundant code in the page. “Low coupling, high cohesion”

  • Closures: Go private

  • .

            var n = 10,
                m = 20;
            var total = n + m;
            var average = (total / 2).toFixed(2);
            console.log(average);
    
            var n = 17,
                m = 28;
            var total = n + m;
            var average = (total / 2).toFixed(2);
            console.log(average);
    
            var n = 189,
                m = 231;
            var total = n + m;
            var average = (total / 2).toFixed(2);
            console.log(average);

Copy the code

Function sum(x, y){… }

  • Name of the sum function (equivalent to a variable, which also declares a sum variable, but stores the value as a function)

  • X or y: parameter (variable), which stores the information passed in the argument and is an entry point provided by the function (reason: to encapsulate this function, much of the information is not clear until the user passes it to me during execution)

  • {… } Function body: the area where the specific function code is written

function sum(x, y) { //console.log(sum); Var logon = logon; var logon = logon; var logon = logon; var logon = logon; var logon = logon; var logon = logon; var logon = logon; var logon = logon; average = average.toFixed(2); console.log(average); }Copy the code

Execute function function (argument 1, argument 2,…)

  • Argument (specific value) : the specific value passed to a function parameter.

sum(17, 28); sum(189, 231); sum(); //x=undefined y=undefined sum(10); //x=10 y=undefined => NaN (); //x=10 y=undefined => NaN (); // if x=10, y=20, sum(10, 20, 30); // if x=10, y=20, sum(10, 20, 30); / / x = 10 y = 20 = > 15.00Copy the code

Parameters are typically treated as default values in a project

  • If condition judgment
Function sum(x, y) {if (x === = undefined); } if (y === undefined) //if (typeof y === "undefined") { y = 0; } var total = x + y, average = total / 2; average = average.toFixed(2); console.log(average); } sum(); // =>0 sum(10); // if x=10, y=0, sum(10, 20); // if x=10, y=0, sum(10, 20); // if x=10, y=20, sum(10, 20, 30); // if x=10, y=20, sum(10, 20, 30); / / = > 15.00Copy the code
  • Logic or | | and logic and &&

    • A | | B first see A is true or false, if A is true return A value, if A is false return the value of B.
    • A &&b first looks at whether A is true or false, returns the value of B if A is true, returns the value of A if A is false.
    • Both appear, && priority than | |.

    Only “0/NaN/ empty string /null/undefined” is false, the rest is true.

The function sum (x, y) {/ / for x = x | | 0; This way, the value of x or y is not only a undefined becomes 0, when the value of x or y is 0 / NaN/empty string will become 0 / null, this method is relatively serious, but it can be processing. X = x | | 0; / / when x is undefined that x is false, returns 0, y = y | | 0; var total = x + y, average = total / 2; average = average.toFixed(2); console.log(average); } sum(); // =>0 sum(10); // if x=10, y=0, sum(10, 20); // if x=10, y=0, sum(10, 20); // if x=10, y=20, sum(10, 20, 30); // if x=10, y=20, sum(10, 20, 30); / / = > 15.00Copy the code
  • In ES6, parameters are assigned default values
    • If we set the parameter to pass no value, then the parameter is the default value after the equals sign,
    • But once values are passed (except for undefined, which takes 0 when the value passed is undefined), nothing is passed as the default.
function sum(x = 0, y = 0) { var total = x + y, average = total / 2; average = average.toFixed(2); // In the function body, you must get the result console.log(average); // In the function body, you must get the result console.log(average); / / "15.00"} sum (10, 20); console.log(average); // Uncaught ReferenceError: ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: Uncaught ReferenceError: UncaughtCopy the code

Exit of a function: return value mechanism

return

  • The return value is whatever comes after return.

  • Do not write return or nothing after return, the default return value is undefined.

  • If a return is encountered in the body of a function, the code below the return will not be executed.

  • Return ‘15.00’ -> return ‘15.00’

function sum(x = 0, y = 0) { var total = x + y, average = total / 2; average = average.toFixed(2); return average; Return '15.00'; //-> return '15.00'; console.log('OK'); } var result = sum(10, 20); // sum(10, 20) returns 15.00 console.log(result); / / = > 15.00Copy the code

Create function normally: declare a variable called fn (function name), except that the stored value is a function.

function fn() {}
Copy the code

Anonymous function (no function name)

  • Function expression: To create a function as a value and assign a value to a variable or other content.

  • Self-executing functions: Creating functions and executing functions are done together.

“Function expression” creates a function: the effect is the same as above (there are some differences in variable promotion)

Var fn = function () {return function () {return function () {}}; var f = fn(); Document.body. Onclick = function () {};Copy the code

Self-executing functions: The first brace holds the function created, and the second brace executes the function

(function (x) { // ... }) (100); // The argument 100 is passed to the parameter x. // In addition to wrapping the function in parentheses to solve syntax errors (because the created function has no name), add ~, +, -,! ~ function (x) {//... } (100);Copy the code

Requirement: When executing a function, the argument value is passed, but the number of arguments passed is “uncertain”. We want to accept the argument information passed by the function.

  • Set parameters: but you need to know the number and order of arguments to be passed.
  • Function built-in argument set Arguments (compatible with all browsers) : This set contains all arguments passed regardless of whether or not arguments are passed (and whether or not arguments are set).
    • If you don’t pass it, it’s an empty set.
    • This collection is an “array of classes.”
  • ES6 in “…” Residual operators (in ES6, not compatible with browsers) : The remaining operators in the function parameters, which can be retrieved from the set in which the rest of the arguments, except those received by the previously set parameters, are placed.
    • If no parameter is defined, all argument information passed is stored in this set.

    • This collection is an “array” collection, and the params variable stores the collection of parameters.

function fn(... params) { console.log(params); //console.log(arguments); //console.log(params,arguments); } fn(); fn(10); fn(10, 20); fn(10, 20, 30);Copy the code

New way to “create functions” in ES6: “arrow functions” “All arrow functions are function expression creation methods”

  • The syntax for creating a function is different.

  • The execution function is consistent. Fn ()

Var XXX = ([parameter])=>{[function body]}Copy the code
  • Arrow function
    • If you have only one parameter, you can leave the parentheses alone

    • If the function body contains only one sentence and the return is XXX, then omit the braces and return…

    • No arguments in the arrow function. (If you want to get information about all arguments passed by the function, you can only use the residual operator “…” if you don’t know how many arguments are passed.) A)

function fn(x) { return x * 10; Var fn = (x) => {return x * 10; }; // If the function body contains only one statement and the return is XXX, omit the braces and return... Var fn = x => x * 10; function fn(x) { return function (y) { return x + y; }; Var fn = x => y => x + yCopy the code