Variables and constants

Variable: the value can be changed;

A variable is not a specific value, but a container or a synonym for storing a specific value. Because the value it stores can be changed, it is called a variable.

A variable is actually just a meaningless name, which represents the value it stores;

A variable can only represent one value

Create a variable

  1. var
  2. functionCreate a function (the function name is also a variable, but the value stored is a function type)
  3. let
  4. constCreate ES6 constants
  5. importExport the required information based on ES6 module specification
  6. classCreate classes based on ES6

Difference between var and let

  1. varThere’s a variable promotion,letThere is noVariable ascension
  2. letYou can’t name it twice
  3. Global scopeletDeclared variableIt has nothing to do with Windows
  4. letThere are temporary dead zones
  5. letCan form block-level scope
/ / syntax:
varVariable name = variable valueletVariable name = variable valueconstVariable name = variable valuefunctionThe function name (){}
Copy the code

Constants: Values are immutable, any one of themSpecific data valuesThey’re all constants. For example, 12 is a constant

A constant cannot be reassigned

	//var Variable name = variable value;
	var num=12;
	//ES6 defines the variable let
	let num2=12;

	// Define constants
	const num3 =12;
	num3 = 13;   Uncaught TypeError: Assigjvulnerabilities to constant variable values cannot be modified
Copy the code

JS data type

Basic data types (value types)

  • number: digital
  • string: string (single or double quotation marks)
  • boolean: Boolean
  • nullNull object pointer
  • undefinedundefined
  • A special data type has been added to ES6:Symbol, unique value

Reference data type

  • objectObject data type
    • {}Common data types
    • []An array of
    • $/ / ^regular
    • The date object
    • MathMathematical objects
    • .
  • functionFunction data type

string

In js, single and double quotation marks are all strings: “aa” =>string; ‘[1, 2, 3]’ = > string

Common methods:

charAt

chartCodeAt

substr

substring

slice

toUpperCase

toLowerCase

indexOf

lastIndexOf

split

replace

match

.

Other types are converted to strings: all but ordinary objects are quoted (arrays are also special)

What is happening

  1. Based on thealert,confirm,prompt,document.writeMethods such asoutputWill convert the output value to a string and print,These output answers must be in single quotes
  2. Based on the+forString splicingwhen
  3. theReference data type valuesintodigitalFirst of allConvert to stringAnd thenConvert to numbers
  4. toObject setting property nameIf it’s not a string, firstConvert to string, and then stored in the object as a property (The property name of an object can only be a number or a string)
  5. Manual callToString, toFixed, Join, StringAnd so on, in order to convert to a string
var n=Math.PI; = >3.141592654
n.toFixed(2) = >'3.14'

var arr=[12.23.34]
arr.join('+') = >'12 + 23 + 34'
Copy the code

Conversion regularity

1. The browser’s default conversion calls toString
2. All except ordinary objects are quoted (arrays are also special)
  • 1 ->'1'(Calling toString manually does not work);
  • NaN -> 'NaN' ;
  • null -> 'null'(Calling toString manually does not work);
  • [] -> '' ;
  • [12] - > '12';
  • [12, 13] - > '12, 13;
  • function fn(){} -> 'function fn(){}' ;
  • new Date().toString() -> '2018.08.27'
No matter what kind of ordinary object, the end result is'[object Object]'

{name:’name’} -> ‘[object object]’

The data type example return
string “foo”.toString() “foo”
digital 1.toString() Uncaught SyntaxError: Invalid or unexpected token
Boolean value false.toString() “false”
undefined undefined.toString() Uncaught TypeError: Cannot read property 'toString' of undefined
null null.toString() Uncaught TypeError: Cannot read property 'toString' of null
String String.toString() “function String() { [native code] }”
Number Number.toString() “function Number() { [native code] }”
Boolean Boolean.toString() “function Boolean() { [native code] }”
Array Array.toString() “function Array() { [native code] }”
Function Function.toString() “function Function() { [native code] }”
Date Date.toString() “function Date() { [native code] }”
RegExp RegExp.toString() “function RegExp() { [native code] }”
Error Error.toString() “function Error() { [native code] }”
Promise Promise.toString() “function Promise() { [native code] }”
Obejct Object.toString() “function Object() { [native code] }”
Math Math.toString() “[object Math]”
A case where calling toString manually does not work
1.toString()  / / an error

let a=1;
console.log(a.toString());	/ / '1'

let a=null;
console.log(a.toString());  / / an error
console.log(null.toString());	/ / an error

let a=undefined;
console.log(a.toString());  / / an error
console.log(undefined.toString());  / / an error
Copy the code

The number of digital

JS adds a NaN of type number to regular numbers

Number(), which converts a value of another data type to Number

1, string to number, from left to right as long as any one appearsNot a valid numeric character“And the end result isNaN

Number(’12’) => 12

Number(’12px’) => NaN

Number(”) => 0

Number(‘ ‘) => 0 Space

Number(‘\n’) => 0 newline character

Number(‘\t’) => 0

2, Boolean to number

  • Number(true) => 1
  • Number(false) => 0

3. Other numbers

  • Number(null) =>0
  • Number(undefined) => NaN
  • Number(”) => 0
  • Number(NaN) => NaN

4. To convert a reference datatype to a number, first convert the reference datatype to a string

To convert a reference datatype to number, first convert the reference datatype to a string (using toString) and then convert the string to number.

Array: [] => ” => 0; [12] => ’12’ => 12; [12,23] => ‘12,13’ => NaN;

Object Number ({aaa: ‘aaa’}) = > NaN: Number ({}) = > ‘[object object]’ = > NaN

Re: /^$/.toString() -> ‘/^$/’ ->NaN

	Number('12') = >12
	Number('12px') = >NaN

	Number(true) = >1
	Number(false) = >0
	Number(null) = >0
	Number(undefined) = >NaN

	Number([]) = >Number(String([])) = >Number(' ') = >0

Copy the code

ParseInt (): converts to an integer

1. When using only one parameter, search for valid numeric characters from left to right until an invalid numeric character is encountered

Converts values of other data types to number, parsing out the integer part of a string

Extraction rules: search from left to right for valid numeric characters, until you encounter non-valid numeric characters (whether there are more or not, don’t look for them), and convert the found digits to digits; ParseInt (‘ 12 px13 ‘) = > 12; parseInt(‘px12’) => NaN

Unrecognized numbers after the decimal point are converted to integers

If it's not a string, it's a string first

Number('12px') = >NaN
parseInt('12px') = >12
parseInt('12px13') = >12
parseInt('12.5 px.) = >12
parseInt('px12') = >NaN
Copy the code

2,When two arguments are usedparseInt(string, radix),radix :2 ~ 36

parameter describe
string A necessity. String to be parsed.
radix Optional. saidThe radix of the number to be parsed. The valueBetween 2 and 36. ifIf this parameter is omitted or its value is 0, the number will be based on 10To resolve. If it starts with “0x” or “0x”, it will be based on 16. ifIf this parameter is less than 2 or greater than 36, parseInt() will return NaN.

Example:

ParseInt (17, 8) corresponds to the conversion of base 17 to base 10 in base 8
1          7
8the1To the power8the0To the power1*8 +7*11is80Power) =15
Copy the code
ParseInt (157, 8) base 8 157 to base 10
1           5             7
8the2To the power8the1To the power8the0To the power1*8*8 + 5*8 +7*1(1is80Power) =111
Copy the code
ParseInt (154, 6) base 6 to base 10
   1           5          4
   6the2To the power6the1To the power6the0To the power1*6*6 + 5*6 + 4*1 = 70
Copy the code

So on

Base 8 a bit is up to 7
Base 2 a bit up to 1
Base 10 a bit up to 9
Any character beyond that is not a valid character.

Base 8 18 = “remainder 8 beyond is invalid after deletion only 1, equivalent to base 8 1 to 10 =” 1

let arr=[1.2.3]
console.log(arr.map(parseInt));			//[ 1, NaN, NaN ]

//parseInt receives:
parseInt(1.0)	// Defaults to 10 radix 1 when radix is 0
parseInt(2.1)	// parseInt() returns NaN when radix is less than 2 or greater than 36
parseInt(3.2)	// When radix is 2, only 01 is valid

Copy the code

ParseFloat (): Converts to decimals that recognize decimal points

Based on parseInt, we can recognize the decimal point and parse out the small (floating point) part of a string

parseInt('12.5 px.) = >12
parseFloat('12.5 px.) = >12.5
parseFloat('px12') = >NaN
Copy the code

NaN:

Not a number: not a valid number, but of type number

1, typeof NaN => ‘number’

NaN is not equal to any other value including itself

NaN === NaN => false ;

NaN plus any data other than a string results in NaN

IsNaN: The only way to detect whether it is a significant number

Is used to check if it is a non-significant number. If it is a non-significant number, return true. The number is false

The only way to check if it is a significant number

When using an isNaN test value, the browser defaults to converting the value to number (using number ()) and then checking if the value is not of the number data type

The isNaN (‘ 12 ‘) = false

Only NaN is not a significant number; the rest are significant numbers

False (numeric) with isNaN: true, false, null, a numeric string, a single-entry array of numbers, because all calls to Number result in numbers

    isNaN([]) = >isNaN(Number([])) = >isNaN(Number(toString([])))   =>  isNaN(Number(' ')) = >isNaN(0) = >false
	isNaN(0) = >falseThe digitalisNaN(NaN) = >trueNot NumbersisNaN('12') = >falseIt's a number, we useisNaNWhen checking for a value other than number, the browser defaults to converting the value to numberNumber()), and then check againisNaN(true) = >isNaN(Number(true)) = >isNaN(0) = >falseThe digitalisNaN(false) = >falseThe digitalisNaN(null) = >falseThe digitalisNaN(undefined) = >isNaN(Number(undefined)) = >isNaN(NaN) trueNot NumbersisNaN([12]) = >falseThe digitalisNaN([12.13]) = >trueNot NumbersisNaN({aaa:9}) = >trueNot NumbersisNaN($/ / ^) = >trueNot NumbersisNaN(function(){}) = >trueNot NumbersCopy the code

Boolean values (JS true or false)

There are only two values :true false

Boolean(): Convert other data types to Boolean data types

There are only five types of false: 0, NaN, empty string, null, and undefined

True: All but the above five are true

Other values are converted to Booleans

Only “0, NaN,” “null, undefined” are converted to false, and the rest are converted to true

Based on the! /!!!!! /BooleanEqual method conversion

All conditions in a conditional judgment are converted to a Boolean value

if(n){
	//=> Convert the value of n to a Boolean value to verify the condition
}

if('3px' + 3) {// select * from '3px3' where ('3px3')
}
Copy the code

! , takes the inverse, first converts the value to a Boolean value, then takes the inverse

Another function of the exclamation mark in JS is to convert a value to a Boolean value, and then to invert

! 1 => false; ! [] => false; ! 0 => true

!!!!! If you take an inverse twice, you take no inverse at all

If you take an inverse of an exclamation point, you have cast the other types to A Boolean. [] => true; !!!!! null =>false ; !!!!! 1 => true;

Null, and undefined

Null: No

Undefined: undefined None

“: Empty string does not have

0: It can also be interpreted as none

Undefined: undefined

  1. Variable promotion stageThe default value is undefined
  2. In strict mode:There is no explicit execution body; this is undefined
  3. Object does not have this property name, the property value is undefined
  4. Function definition parameters do not pass values: The default is undefined
  5. The function returns no value (no return or just return;)Undefined is returned by default

Null: empty

  1. Manually set the value of a variable or an attribute of an object to NULL.
  2. In the JS DOM element fetchIf theThe specified element object was not retrieved, the result is usually null
  3. Object.prototype.__proto__Is also null
  4. No result was captured when the re was capturedThe default is also null

Document. parentNode => Has this property but cannot find null

Document. parentNode => Undefined property (parentNode does not exist)

The difference between an empty string and null

To plant trees

An empty string is a dug hole with no seeds,

Null is not digging a hole

Empty strings open up memory relative to null and consume a little bit of performance

Null and undefined

Null is generally usedNo assignment at the moment, expected later

In JS, null is usually manually assigned to a value of NULL, and then assigned to a specific value

Undefined: completely unexpected, generally not manual control, most of the browser’s own empty; It may or may not be assigned

Common object Object

var obj={name:’aa’,age:19}

Each object is composed of zero to multiple sets of attribute names (key, key) : attribute values (value, value), or multiple sets of key-value pairs separated by commas

Properties are used to describe the characteristics of the current object, and the property value is the description of this feature

The property name of an object can only be a string or a number, and the stored property value can be any data type

When we store property names that are not strings or numbers, the browser converts the value to a string (toString) and stores it; Obj [{}]=300 Store the result after {}.toString() as the property name. Obj [‘[object object]’]=300

Obj [{}] => convert the object to the string ‘[object object]’, and then retrieve the previously stored 300

Operation:

Attribute name. Attribute value. Omitted single and double quotes for attribute names, obj.name

Attribute name [attribute value], cannot omit single and double quotes, obj[‘name’]

If the attribute name is a number:

Obj. 0 no; Obj [0] or obj[‘0’], obj[0] === obj[‘0’]

If the attribute name of the operation does not exist in the object, the result is undefined

Set, modify:

Aaa =18; obj. Aaa =18; obj. Aaa =18; obj[‘aaa’]=19;

delete: delete obj. Aaa

False delete: makes the property null, but the property is still in the object: obj.aaa=null

True delete: Removes the entire property from the object, delete obj.aaa;

var obj={name:'aaa'.age:18}
var name='bbb'


obj.name   => 'aaa'Take the name attribute obj['name'] = >'aaa'Obj [name] =>undefined'bbb'Property where name is a variableCopy the code

An array of

Var arr = [12, 13]

Enclosed in brackets, containing zero to more than one item

The array object’s property name is a number, and we give the number property name the index of the current object

To obtain

arr[0]

arr[‘0’]

Arr.0 does not report an error

regular

var reg=/^$/

Consists of metacharacters to form a complete re

Symbol

The value created is unique, and there is no equal value

var a=Symbol('aaa')

console.log(a)    //Symbol('aaa')

var b=Symbol('aaa')

console.log(b)    //Symbol('aaa')

console.log(a==b)    //false
Copy the code