Note source: Still silicon Valley latest version of the full set of JavaScript basic tutorial complete version (140 sets of actual combat teaching,JS from entry to master)_ bilibili _bilibili

[TOC]

JS based

1, JS writing position

We can put js code in the onclick property of the tag and it will execute when we click the button

<button onclick="alert(\"Fuck! Do not touch me! \ ") "></button>
Copy the code

You can put the JS code in the href attribute of the hyperlink so that when the hyperlink is clicked, the JS code is executed

<a href="alert(\"What's up.man? \ ") ">Try to click me</a>
Copy the code

Although they can be written in the attributes of tags, they are not recommended because they are structure-behavior coupled and are not easy to maintain

Js code can be written to script tags

<script type="text/javascript">
    alert("I'm inner script.");
</script>
Copy the code

You can write JS code to an external JS file and import it via script tags

<script src="/js/script.js" type="text/javascript"></script>
Copy the code

Once the script tag is used to import external files, it cannot be written in code, even if it is written in a browser

Create a new script tag for internal code if necessary

2. JS annotations

Multiline comment

Multi-line comments, the contents of which are not executed but can be viewed in the source code

/* Multiline comments... Multi-line comments... Multi-line comments... * /
Copy the code

Single-line comments

// Single-line comment
Copy the code

3. Pay attention

  1. JS is case sensitive

  2. Each statement in JS is preceded by a semicolon; At the end

    If the semicolon is not written, the browser automatically adds it, but it consumes some system resources, and sometimes the browser adds the wrong semicolon, so it must be written during development

  3. Multiple whitespace and line breaks are ignored in JS, so we can format our code with whitespace and line breaks

Literals and variables

literal

Literals are immutable values

Literals can be used directly, but we usually don’t use literals directly

variable

Variables can be used to hold literals, and the value of a variable can be changed at will

So in development, a literal is stored in a variable, and literals are rarely used directly

Literals can be described by variables

// Declare a variable: Use the var keyword to declare a variable in JS
var a;
// Assign a value to a variable
a = 123;
a = 456;
a = 123124223423424;
// Declare and assign simultaneously
var b = 789;
var c = 0;
var age = 80;
console.log(age);
Copy the code

5. Identifiers

Anything in JS that we can name ourselves can be called an identifier

For example, variable names, function names, and attribute names are identifiers

When naming an identifier, follow the following rules:

  1. The identifier can contain letters, digits, underscores, and $
  2. Identifiers cannot start with a number
  3. The identifier cannot be a key or reserved word in ES
  4. Identifiers are generally hump nomenclature
    • The first letter of each word is capitalized and the rest of the letters are lowercase

The keyword

if else do while for
break continue try catch finally
throw true false function return
switch case null typeof instanceof
new var void in with
default debugger delete this

Reserved words

class enum extends super const export
import implements let private public yield
interface package protected static

Other recommended identifiers

boolean byte short char int long
float double String Boolean Number Object
Date Array Math Error SyntaxError EvalError
TypeError URIError RangeError ReferenceError encodeURI decodeURI
parselnt parseFloat NaN isNaN undefined transient
throws native goto eval JSON Infinity
arguments isFinite volatile abstract RegExp Function
synchronize final encodeURICOmponent decodeURIComponent

The identifiers stored in JAVASCRIPT are actually encoded in Unicode, so in theory all utF-8 contents can be used as identifiers

6. Data types

Datatypes are literal types, and there are six types of datatypes in JS

Basic data types String string
Number The numerical
Boolean Boolean value
Null A null value
Undefined undefined
Reference types Object object

String, Number, Boolean, Null and Undefined belong to basic data types, while Object belongs to reference data types

String String

In JS, strings need to be enclosed in quotes, either single or double, but do not mix them

The same type of quotation marks cannot be nested, nor can double or single quotation marks be placed

We can use \ as an escape character in strings, and when representing special symbols, we can use \ to escape

  • \"said"
  • \ 'said'
  • \nnewline
  • \ttabs
  • \ \said\

The Number of numerical

In JS, all values are of type Number, including integers and floating point numbers (decimals).

You can use the typeof operator to check the typeof a variable. Syntax: Typeof variables

  • Returns when the string is checkedstring
  • Returns when the value is checkednumber

MAX_VALUE

Number.MAX_VALUE=1.7976931348623157e+308

If the Number represented by Number exceeds the maximum value, an Infinity is returned

var a = Number.MAX_VALUE * Number.MAX_VALUE;
console.log(a); // Infinity
Copy the code

MIN_VALUE

MIN_VALUE= 5E-324

var a = Number.MIN_VALUE * Number.MIN_VALUE;
console.log(a); / / 0
Copy the code

Infinity

  • InfinityPlus infinity
  • -InfinityMinus infinity

Using Typeof check, Infinity returns Number

var a = Number.MAX_VALUE * Number.MAX_VALUE;
console.log(typeof a); // number
Copy the code

NaN

NaN is A special Number that means Not A Number

var a = 'abc' * 'def';
console.log(a); // NaN
Copy the code

Checking a NaN using Typeof also returns number

var a = 'abc' * 'def';
console.log(typeof a); // number
Copy the code

Operation precision

In JS integer operation can guarantee accuracy

If you use JS for floating point operations, you may get an imprecise result

var a = 0.1 + 0.2;
console.log(a); / / 0.30000000000000004
Copy the code

So do not use JS for high accuracy requirements of the operation

Boolean Boolean value

There are only two booleans, mainly used for logical judgment

  • trueSaid really
  • falseSaid the false

When typeof is used to check a Boolean value, Boolean is returned

Null

There is only one value of type Null, which is Null

The value null is used specifically to represent an empty object

When typeof is used to check for a null value, object is returned

var a3 = null;
console.log(a3); // null
console.log(typeof a3); // object
Copy the code

Undefined

The only value of Undefined is undefind

When a variable is declared but no value is assigned to it, its value is undefined

When typeof checks for a undefined object, undefined is also returned

var a4;
console.log(a4); // undefind
console.log(typeof a4); // undefind
Copy the code

7. Cast

To cast a data type to another data type

Type conversion refers to converting other data types to String, Number, and Boolean

7.1. Convert other data types to String

Method 1: Call toString() on the converted data type

This method does not affect the original variable and returns the result of the transformation

// Number converts to String
var a1 = 123;
var b1 = a1.toString();
console.log(typeof a1); // number
console.log(typeof b1); // string
// Boolean converts to String
var a2 = true;
var b2 = a2.toString();
console.log(typeof a2); // boolean
console.log(typeof b2); // string
Copy the code

Note, however, that null and undefined do not have toString() and will return an error if their methods are called

// Null converts to String
var a3 = null;
var b3 = a3.toString(); // UncaughtTypeError: Cannot read property 'toString' of null
console.log(typeof a3); 
console.log(typeof b3);
// Undefined is converted to String
var a4 = undefined;
var b4 = a4.toString(); // UncaughtTypeError: Cannot read property 'toString' of undefined
console.log(typeof a4); 
console.log(typeof b4);
Copy the code

Method 2: Call the String() function and pass the converted data to the function as an argument

When using String() to cast, the toString() method is actually called for Number and Boolean

But for null and undefined, the toString() method is not called

  • nullConvert directly to"null"
  • undefinedConvert directly to"undefined"
// Number converts to String
var a1 = 123;
var b1 = String(a1);
console.log(typeof a1); // number
console.log(typeof b1); // string
// Boolean converts to String
var a2 = true;
var b2 = String(a2);
console.log(typeof a2); // boolean
console.log(typeof b2); // string
// Null converts to String
var a3 = null;
var b3 = String(a3);
console.log(typeof a3); // object
console.log(typeof b3); // string
// Undefined is converted to String
var a4 = undefined;
var b4 = String(a4);
console.log(typeof a4); // undefined
console.log(typeof b4); // string
Copy the code

7.2. Convert other data types to Number

Method 1: Use the Number() function

  • String –> number

    • If it is a purely numeric string, it is converted directly to a number
    • If there is non-numeric content in the string, convert toNaN
    • If the string is an empty string or a string full of Spaces, it is converted to0
    // ** The Number() function **
    // A numeric string
    var a1 = '123';         
    a1 = Number(a1);
    console.log(typeof a1); // number
    console.log(a1); 	    / / 123
    // Non-numeric content
    // var a2 = 'abc';         
    var a2 = undefined;
    a2 = Number(a2);
    console.log(typeof a2); // number
    console.log(a2);        // NaN 
    / / an empty string
    // var a3 = ' ';      
    var a3 = null;       
    a3 = Number(a3);        
    console.log(typeof a3); // number
    console.log(a3);        / / 0
    Copy the code
  • Boolean –> numbers

    • trueinto1
    • falseinto0
    var a4 = true;
    a4 = Number(a4);
    console.log(typeof a4); // number
    console.log(a4);        / / 1
    var a5 = false;
    a5 = Number(a5);
    console.log(typeof a5); // number
    console.log(a5);        / / 0
    Copy the code

Method two: Specifically for strings

  • parseInt()Convert a string to an integer: You can take the valid integer part of a string and convert it to Number
  • parseFloat()Convert a string to a floating point Number: You can take the valid decimal part of a string and convert it to a Number
  • If used for non-stringsparseInt()orparseFloat(), it will first convert it to String and then operate
var a1 = "123";
a1 = parseInt(a1);
console.log(typeof a1); // number
console.log(a1);        / / 123
var a2 = "123.456";
a2 = parseInt(a2);
console.log(typeof a2); // number
console.log(a2);        / / 123
var a3 = "123px";
a3 = parseInt(a3);
console.log(typeof a3); // number
console.log(a3);        / / 123
// var a4 = null;
// var a4 = undefined;
// var a4 = '';
// var a4 = 'abc';
// var a4 = true;
var a4 = false;
a4 = parseInt(a4);
console.log(typeof a4); // number
console.log(a4);        // NaN
Copy the code

7.3. Convert other data types to Boolean

Method 1: UseBoolean()function

  • Numbers — > Boolean
    • In addition to0andNaNThe rest aretrue
  • String — > Boolean
    • All but empty stringstrue
  • nullandundefinedWill be converted tofalse
  • Objects are also converted totrue
// -- number -- > Boolean
// - all except '0' and 'NaN' are 'true'
// var a1 = 0;
var a1 = NaN;
a1 = Boolean(a1);
console.log(a1); // false
var a2 = 123;
a2 = Boolean(a2);
console.log(a2); // true
// string -- > Boolean
// - all but empty strings are true
var a3 = "123";
a3 = Boolean(a3);
console.log(a3); // true
var a4 = "";
a4 = Boolean(a4);
console.log(a4); // true
var a5 = "";
a5 = Boolean(a5);
console.log(a5); // false
// - 'null' and 'undefined' are both converted to 'false'
// var a6 = null;
var a6 = undefined;
a6 = Boolean(a6);
console.log(a6); // false
Copy the code

Method 2: Implicit type conversion

Convert any data type to a Boolean by performing two non-operations on it (described in the next section)

var a = "123";
varb = !! a;console.log("a="+a+",b="+b); // a=true,b=true
Copy the code

8, supplement

In JS, if you need to represent hexadecimal numbers, you need to start with 0x

If you want to represent a base 8 number, you need to start with 0

If you want to represent numbers in base 2, you need to start with 0b, but not all browsers support this

// A hexadecimal number
var a = 0x10;
console.log(a); / / 16
a = 0xff;
console.log(a); / / 255
a = 0xCafe;
console.log(a); / / 51966
a = "0x70";
a = parseInt(a,16);
console.log(a); / / 112
// Octal digits
a = 070;
console.log(a); / / 56
a = "070";
a = parseInt(a,8);
console.log(a); / / 56
// Binary number
a = 0b10;
console.log(a); / / 2
Copy the code