Javascript code can be placed directly anywhere in the web page, usually in.

<html>
<head>
  <script>
    alert('Hello, world');
  </script>
</head>
<body>
  ...
</body>
</html>
Copy the code

The included code is JavaScript code that will be executed directly by the browser.

The second way is to put the JavaScript code in a separate.js file and then in HTML by importing this file:

<html>
<head>
  <script src="/static/js/abc.js"></script>
</head>
<body>
  ...
</body>
</html>
Copy the code

In this case, /static/js/abc.js is executed by the browser.

Putting JavaScript code in a single.js file makes it easier to maintain the code, and multiple pages can each reference the same.js file. You can introduce multiple.js files on the same page, and you can write them multiple times on the page, with the browser executing them in sequence. // Comments that start with a double slash to the end of the line are comments. Comments are intended for viewing and will be ignored by browsers

The basic grammar

JavaScript syntax is similar to the Java language, with each statement beginning with; The statement block ends with {… }.

if (2 > 1) { x = 1; y = 2; z = 3; if (x < y) { z = 4; } if (x > y) { z = 5; }}Copy the code

Note that JavaScript is strictly case sensitive, and if you get case wrong, your program will report an error or run improperly.

The data type

Computers can process far more than numerical values, but also text, graphics, audio, video, web pages and other kinds of data, different data, need to define different data types.

A Number,

JavaScript does not distinguish between integer and floating point numbers and uses Number as a representation. The following are valid Number types:

123; // integer 123 0.456; // float 0.456 1.2345e3; // scientific notation represents 1.2345x1000, equivalent to 12345-99; / / negative NaN; // NaN indicates Not a Number, and NaN indicates Infinity when the result cannot be calculated. // Infinity means Infinity, and Infinity means Infinity when the Number exceeds the maximum JavaScript Number can representCopy the code

Because computers use binary, it is sometimes convenient to use hexadecimal integers, which are represented by the 0x prefix and 0-9, a-f, such as 0xFF00, 0xA5b4C3d2, and so on, which are identical to decimal values. Number can perform four operations directly, and the rules are the same as mathematics:

1 + 2; // 3 (1 + 2) * 5/2; // 7.5 2/0; // Infinity 0 / 0; // NaN 10 % 3; // 1 10.5% 3; / / 1.5Copy the code

Note that % is a remainder operation.

2. String

Strings are arbitrary text enclosed in single or double quotation marks, such as’ ABC ‘, “xyz”, and so on. Note that ” or “” are themselves only representations, not part of a string, so the string ‘ABC’ has only a, B, and c characters.

Boolean value

Boolean values and Boolean algebra representation is exactly the same, a Boolean value can only have two values, either true or false, can be directly expressed by true and false, or can be calculated by Boolean operations:

true; // This is a true value false; // This is a false value 2 > 1; // This is a true value 2 >= 3; // This is falseCopy the code

The && operation is and and is true only if everything is true:

true && true; // The && statement evaluates to true, true && false; // The && statement evaluates to false false && true && false; // The && statement evaluates to falseCopy the code

| | operations is or operations, as long as one is true, | | operation result is true:

false || false; / / the | | statement results to false true | | false; / / the | | statement calculation result is true or false | | true | | false; / / the | | statement results to trueCopy the code

! An operation is not an operation, it is a unary operator that changes true to false and false to true:

! true; // Result is false! false; // The result is true! 2 > (5); // Result is trueCopy the code

When we compare numbers, we can get a Boolean from the comparison operator:

2 > 5; // false
5 >= 2; // true
7 == 7; // true
Copy the code

The second is the === comparison, which does not automatically convert data types, returns false if the data types are inconsistent, and compares if they are.

Another exception is NaN. This particular Number is not equal to all other values, including itself: NaN === NaN; // false The only way to determine NaN is through the isNaN() function: isNaN(NaN); // true

Null, and undefined

Null represents an “empty” value, which is different from 0, which is a numeric value, which represents a string of length 0, and the empty string “”, which represents” empty “. There is also a null – like undefined, which means “undefined”. In most cases, we should use NULL. Undefined is useful only if the function argument is passed.

An array of

An array is a set of sequential collections, each value of which is called an element. JavaScript arrays can contain any data type. Such as:

[1, 2, 3.14, 'Hello', null, true];
Copy the code

The array above contains six elements. Arrays are represented by [], and elements are separated by,. Another way to create arrays is through the Array() function: new Array(1, 2, 3); // Creates arrays [1, 2, 3] however, it is highly recommended to use [] directly for readability purposes.

The elements of an array can be accessed by index. Note that the index starts at 0:

Var arr = [1, 2, 3.14, 'Hello', null, true]; arr[0]; // return the element with index 0, that is, 1 arr[5]; // return the element with index 5, true arr[6]; // Index out of range, return undefinedCopy the code

Three, objects,

JavaScript objects are an unordered set of key-values, such as:

var person = {
    name: 'Bob',
    age: 20,
    tags: ['js', 'web', 'mobile'],
    city: 'Beijing',
    hasCar: true,
    zipcode: null
};

Copy the code

The keys of JavaScript objects are strings, and the values can be any data type. The person object defines six key-value pairs, each of which is called an attribute of the object. For example, the Person name attribute is ‘Bob’ and the Zipcode attribute is null. To get the properties of an object, we use object variables. The way the attribute name works:

person.name; // 'Bob'
person.zipcode; // null

Copy the code

Four, variables,

The concept of variables is basically the same as equation variables in junior high school algebra, except that in computer programs, variables can be not only numbers, but also any data type. Variables in JavaScript are represented by a variable name, which is a combination of uppercase and lowercase letters, digits, $, and _, and cannot start with a number. Variable names cannot also be JavaScript keywords, such as if, while, etc. Declare a variable with the var statement, as in:

var a; Var $b = 1; var $b = 1; $b = 1 var s_007 = '007'; // s_007 is a string var Answer = true; // Answer is a Boolean value true var t = null; // the value of t is null and the variable name can also be used in Chinese, but please do not trouble yourself.Copy the code

In JavaScript, variables are assigned with the equal sign =. Variables can be assigned to any data type, the same variable can be assigned repeatedly, and can be different types of variables, but be sure to declare var only once, for example: var a = 123; // the value of a is an integer 123 a = ‘ABC’; // a becomes a string. Do not equate an assignment statement with a mathematical equal sign. For example: var x = 10; x = x + 2; If you understand x = x + 2 mathematically, it is not true anyway. In the program, the assignment statement first evaluates the expression x + 2 on the right to obtain the result 12, and then assigns to the variable x. Since the value of x was 10, the value of x becomes 12 after reassignment. To display the contents of a variable, use console.log(x), and open Chrome’s console to see the results. The advantage of using console.log() instead of alert() is to avoid annoying pop-up dialog boxes.

string

Multiline strings: Because multiline strings are too cumbersome to write with \n, the latest ES6 standard adds a new way to express multiline strings, using backquotes… Said:

'This is a multi-line string';Copy the code

object

A JavaScript object is an unordered collection data type consisting of several key-value pairs. JavaScript objects are used to describe objects in the real world. For example, to describe Xiao Ming, the naughty child, we can use several key-value pairs to describe him:

Var xiaoming = {name: 'xiaoming ', birth: 1990, school: 'No.1 Middle school ', height: 1.70, weight: 65, score: null};Copy the code

JavaScript uses a {… } represents an object, and the key-value pairs are declared in the form XXX: XXX, separated by,. Note that the last key-value pair does not need to be appended at the end, and some browsers (such as earlier versions of Internet Explorer) will report an error if it is appended. The above object declares a name property with a value of ‘xiao Ming’, a birth property with a value of 1990, and several other properties. If xiaoming is oming, we can use xiaoming to get xiaoming’s property:

xiaoming.name; // 'xiaoming' birth; / / 1990Copy the code

cycle

There are two types of JavaScript loops, the first is the for loop, which loops through blocks of statements through initial, end, and increment conditions:

var x = 0; var i; for (i=1; i<=10000; i++) { x = x + i; } x; / / 50005000Copy the code

Let’s examine the control conditions for the for loop:

  • I =1 that’s the initial condition, I =1;
  • I <=10000 is the judgment condition. If it is satisfied, the cycle will continue. If it is not satisfied, the cycle will exit.
  • I ++ this is the increment condition after each loop. Since the variable I increases by 1 after each loop, it will eventually exit the loop after several loops without meeting the judgment condition I <=10000.

Object-oriented programming

JavaScript sets a prototype for each object it creates, pointing to its prototype object.

Var xiaoming = {name: 'xiaoming ', birth: 1990, height: 1.70,};Copy the code

JavaScript uses a {… } represents an object. A JavaScript object is an unordered collection data type consisting of key-value pairs. Xiaoming: name = ‘xiaoming’; birth = 1990; xiaoming: birth = 1990;

xiaoming.name; // 'xiaoming' birth; / / 1990Copy the code

When we access an Object’s property using obj.xxx, the JavaScript engine looks for the property on the current Object. If not, it looks for the property on its prototype Object. If not, it goes all the way back to the Object.prototype Object. I have to return undefined.

Prototype-based languages?

JavaScript is often described as a prototype-based language — each object has a prototype object from which the object is a template and inherits methods and properties.

function doSomething(){}
doSomething.prototype.foo = "bar"; // add a property onto the prototype
var doSomeInstancing = new doSomething();
doSomeInstancing.prop = "some value"; // add a property onto the object
console.log( doSomeInstancing );
Copy the code