JavaScript basics
In HTML, JavaScript code must be placed between tags.
The script tag can be placed anywhere in the head or body or for external references.
Four ways to output
-
Use window.alert() to write to the alert box
-
Write HTML output using document.write()
for testing only
-
Write HTML elements using innerHTML
document.getElementById(id).innerHTML = ;
-
Use console.log() to write to the browser console
statement specification
End with a semicolon; add spaces to the left and right of the operator; the code is controlled within 80 characters, and it is best to break the line after the operator;
var x,y,z;
x = 7;
y = 2;
z = x + y;
var
The keyword creates a new variable, the variable stores the data value
xyz is the naming identifier of the variable, create multiple variables and separate them with commas
Identifiers are very sensitive to case. There have been three ways to write multiple words to form an identifier
1.ab (all lowercase) 2.a_b (all lowercase) 3.ab (the first letter of each word is capitalized)
And we recommend ab (only the first letter of the b word is capitalized)
In addition , there are restrictions on the naming of identifiers :
-
The first character must be a letter, underscore (-), or dollar sign ($), butIt is more recommended to start with a letter
-
Name contains letters, numbers, underscores, or dollar signs
-
Reserved words (such as JavaScript keywords) cannot be used as variable names
= 号
for assigning values to variables
scope
Keywords: let and const
global scope
Variables declared globally (outside a function) have global scope and can be accessed anywhere in a JavaScript program
function scope
Variables declared (within a function) have function scope and can only be accessed within the function in which they are declared
block scope
let
Key words
{
let x = 10;
}
// 此处不可以使用 x
//在块 {} 内声明的变量无法从块外访问
var x = 10;
// 此处 x 为 10
{
let x = 6;
// 此处 x 为 6
}
// 此处 x 为 10
var let mixed use, variables redeclared in the block will not redeclare variables outside the block
scope
JavaScript-------JavaScript environment
HTML------window
Keywords: var and let
The global variable defined by var belongs to the window object
The global variable defined by let does not belong to the window object
restate
Only var can override var or redeclare via let in a different scope
Key wordsconst
Variables defined by const are similar to let variables, but cannot be reassigned
const variables must be assigned a value when declared
const PI = 3.14159265359;
It doesn't define a constant value, it defines a constant reference to a value.
eg:
// 创建 const 对象:
const car = {
type:"porsche", model:"911", color:"Black"};
// 您可以更改属性:
car.color = "White";
// 您可以添加属性:
car.owner = "Bill";
//但无法重新为常量对象赋值
car = {
type:"Volvo", model:"XC60", color:"White"}; // ERROR
Redeclaration only allows redeclaration in a different scope or block
operator precedence
Calculate from left to right
* and % are higher than + and -
type of data
value
JavaScript has only one numeric type, and the decimal point is optional
precision
Integers (without exponents or scientific notation) are rounded to 15 digits
The maximum number of decimals is 17 digits, but floating-point arithmetic is not always 100% accurate
var x = 0.2 + 0.1; // x 将是 0.30000000000000004
var x = (0.2 * 10 + 0.1 * 10) / 10; // x 将是 0.3
Very large or small values can be written in scientific notation:
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
Boolean values: true and false
toString() method
Output numbers as hexadecimal, octal, or binary
var myNumber = 128;
myNumber.toString(16); // 返回 80
myNumber.toString(8); // 返回 200
myNumber.toString(2); // 返回 10000000
Returns a value as a string, all numeric methods can be used with any type of number (literal, variable or expression)
var x = 123;
x.toString(); // 从变量 x 返回 123
(123).toString(); // 从文本 123 返回 123
(100 + 23).toString(); // 从表达式 100 + 23 返回 123
toExponential() returns a string value containing the number rounded and using exponential notation.
parameter defines the number of characters after the decimal point
toFixed() returns a string value containing a number with the specified number of decimal places
toPrecision() returns a string value containing numbers of the specified length
valueOf() returns a value as a value valueOf() method
Number() can be used to convert JavaScript variables to numbers
parseInt() parses a string and returns a value. Spaces are allowed. returns only the first number
parseFloat() parses a string and returns a value. Spaces are allowed. returns only the first number
numeric attribute
MAX_VALUE | Returns the largest number possible in JavaScript. |
---|---|
MIN_VALUE | Returns the smallest number possible in JavaScript. |
NEGATIVE_INFINITY | Represents negative infinity (returned on overflow). |
NaN | Represents a Not-a-Number value ("Not-a-Number"). |
POSITIVE_INFINITY | Represents infinity (returned on overflow). |
string
Surrounded by single or double quotes.
Special characters
’ | ’ | apostrophe |
---|---|---|
" | " | Double quotes |
\ | \ | backslash |
\ acts on the string, it will not make the code break, it is best to add it after the operator
method:
The length property returns the length of the string
search method
The indexOf() method returns the index (position) of the first occurrence of the specified text in the string
The lastIndexOf() method returns the index of the last occurrence of the specified text in the string
Both indexOf() and lastIndexOf() return -1 if the text is not found, and both methods accept as the second parameter the search starting position
The search() method searches for a string of specific values and returns the matching position, and cannot set the second start position parameter
The match() method searches a string for a match based on a regular expression and returns the match as an Array object
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g) // 返回数组 [ain,ain,ain]
The includes() method returns true if the string contains the specified value
The startsWith() method returns true if the string starts with the specified value, otherwise it returns false
The endsWith() method returns true if the string ends with the specified value, otherwise returns false
Three ways to extract part of a string:
-
slice(start, end)
slice() extracts a portion of a string and returns the extracted portion in a new string
This method sets two parameters: start index (start position), end index (end position)
-
substring(start, end)
substring() is similar to slice()
The difference is that substring() cannot accept negative indices
-
substr(start, length)
substr() is similar to slice()
The difference is that the second parameter specifies the length of the extracted part
The replace() method replaces the value specified in the string with another value
toLowerCase() converts the string to lowercase
concat() concatenates two or more strings
The trim() method removes whitespace from both ends of the string
The charAt() method returns the string at the specified subscript (position) in the string
The charCodeAt() method returns the unicode code of the character at the specified index in the string
split()
split() converts a string to an array
Adding numbers and strings
Both addition and concatenation in JavaScript use the + operator.
Add numbers with numbers. Strings are concatenated.
number + number = number
string + string = string
number + string = string
Number + Number + String = Number + String = String
string + number + number + number = string
NaN is a JavaScript reserved word that indicates that a number is not valid.
Trying to divide by a non-numeric string gets NaN (Not a Number)
var x = 100 / "Apple"; // x 将是 NaN(Not a Number)
isNaN(x); // 返回 true,因为 x 不是数
var y= 100 / "10"; // y 将是 10
var m = NaN,n = "5";
var k = m + n; // k 将是 NaN5
var z = NaN,x = 5;
var k = z + x; // k 将是 NaN
typeof NaN; // 返回 "number"
typeof Infinity; // 返回 "number"
Infinity (or -Infinity) is what JavaScript returns when calculating a number outside the range of the largest possible number
Dividing a number by 0 (zero) also produces Infinity
string template
Use backticks (``)
interpolation
Template literals provide an easy way to insert variables and expressions into strings
${
...}
array
JavaScript arrays are written in square brackets, and the items of the array are separated by commas
var cars = ["Porsche", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
var name = cars[0]; //访问 cars 中的首个元素的值
cars[0] = "Opel"; //修改 cars 中的首个元素
document.getElementById("demo").innerHTML = cars; //引用数组名来访问完整数组
cars.push("LH"); //添加一个新元素
cars[cars.length] = "LH";//添加一个新元素
cars[3] = "LH"; //添加一个新元素
Arrays are special types of objects, and you can store variables of different types in the same array (functions and arrays are both fine)
iterate over the array
for loop
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
Array. foreach() function
var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value) {
text += "<li>" + value + "</li>";
}
Many programming elements support named indexed arrays.
Arrays with named indices are known as associative arrays (or hashes).
JavaScript does not support arrays with named indices.
In JavaScript, arrays can only be indexed numerically
object
JavaScript objects are written using curly braces.
Object properties are name : value pairs, separated by commas.
var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};
this keyword
access object
objectName.propertyName //访问对象属性
objectName["propertyName"] //访问对象属性
objectName.methodName() //访问对象方法
name = person.fullName(); //访问对象方法
typeof operator
The typeof operator returns the type of a variable or expression:
- string
- number
- boolean
- undefined
- function (function)
- object (object, array, or null)
On the difference between Undefined and Null
Undefined is equal to null in value, but not in type:
typeof undefined // undefined
typeof null // object
null === undefined // false 类型不等
null == undefined // true 值相等