The most complete JavaScript learning summary

小云云
Release: 2018-01-09 09:17:05
Original
9097 people have browsed it

This article mainly shares with you a summary of JavaScript learning (1) ECMAScript, BOM, DOM (core, browser object model and document object model). JavaScript is a scripting language that is interpreted and executed. It is a dynamic type and weak type. , a prototype-based language with built-in support for types, which follows the ECMAScript standard. Its interpreter is called the JavaScript engine, which is part of the browser and is widely used in client-side scripting languages. It is mainly used to add dynamic functions to HTML.

1. Introduction to JavaScript

JavaScript is a scripting language that is interpreted and executed. It is a dynamically typed, weakly typed, prototype-based language with built-in support for types. It follows the ECMAScript standard. Its interpreter is called the JavaScript engine, which is part of the browser and is widely used in client-side scripting languages. It is mainly used to add dynamic functions to HTML.

Almost all mainstream languages can be compiled into JavaScript and can then be executed in browsers on all platforms. This also reflects the power of JavaScript and its importance in web development. Such as Blade: a Visual Studio extension that can convert C# code to JavaScript, and Ceylon: a modular, statically typed JVM language that compiles to JavaScript.

JavaScript is a language that can run on both the front end and the backend. For example, Node.js is a JavaScript running environment based on the Chrome V8 engine (similar to Java or .NET). Node.js uses an event-driven, non-blocking I/O model, making it lightweight and efficient.

1.1. JavaScript composition

ECMAScript describes the syntax and basic objects of the language, such as types, operations, flow control, and object-oriented , exceptions, etc.

Document Object Model (DOM) describes the methods and interfaces for processing web content.

Browser Object Model (BOM) describes the methods and interfaces for interacting with the browser.

JavaScript is composed of objects, and everything is an object.

1.2. Features of JavaScript scripting language

a) Interpreted scripting language. JavaScript is an interpreted scripting language. Languages such as C and C++ are compiled first and then executed, while JavaScript is interpreted line by line during the running of the program.

Object-based. JavaScript is an object-based scripting language that can not only create objects but also use existing objects.

b), simple. The JavaScript language uses weakly typed variable types and does not impose strict requirements on the data types used. It is a scripting language based on Java's basic statements and controls, and its design is simple and compact.

c), dynamic. JavaScript is an event-driven scripting language that can respond to user input without going through a Web server. When visiting a web page, JavaScript can directly respond to these events when the mouse is clicked, moved up or down, or moved in the window.

d), cross-platform. JavaScript scripting language does not depend on the operating system and only requires browser support. Therefore, after writing a JavaScript script, it can be brought to any machine for use, provided that the browser on the machine supports the JavaScript scripting language. Currently, JavaScript is supported by most browsers.

2. ECMAScript (JavaScript core and syntax)

2.1, ECMAScript definition

1), ECMAScript is a standard (European Computer Manufacturers Association), JavaScript is just its One implementation, other implementations include ActionScript (Flash script)

2), ECMAScript can provide core script programming capabilities for different types of host environments, that is, ECMAScript is not bound to a specific host environment, such as JavaScript The host environment is a browser, and the host environment of AS is Flash. ,

3), ECMAScript describes the following: syntax, types, statements, keywords, reserved words, operators, objects, etc.

2.2, data types

in Use the var keyword in JS to declare variables, and the type of the variable will be determined based on the value assigned to it (dynamic type). Data types in JS are divided into primitive data types (5 types) and reference data types (Object type).

1) 5 primitive data types: Undefined, Null, Boolean, Number and String. It should be noted that strings in JS are primitive data types.

2) typeof operator: Check the variable type. Calling the typeof operator on a variable or value will return one of the following values:

    • undefined – if the variable Is of type Undefined

    • boolean – if the variable is of type Boolean

    • number – if the variable is of type Number

    • string – if the variable is of type String

    • #object – if the variable is of type reference or Null

3) Solve the reference type judgment problem through the instanceof operator

4) Null is considered a placeholder for the object, and the typeof operator returns "object" for the null value.

5) Original data type and reference data type variables are stored in memory as follows:

memory of datatype in js

#6) The definition of type in JS: a set of values. For example, there are two values of Boolean type: true and false. Both Undefined and Null types have only one value, which are undefined and null respectively.

The Null type has only one value, which is null; the Undefined type also has only one value, which is undefined. Both null and undefined can be used directly in JavaScript code as literals.

null is related to object reference and represents an empty or non-existent object reference. When a variable is declared but no value is assigned to it, its value is undefined .

The undefined value will appear in the following situations:

Get an attribute from an object. If neither the object nor the objects in the prototype chain have the attribute, the attribute's The value is undefined.

If a function does not explicitly return a value to its caller through return, its return value is undefined. There is a special case when using new.

A function in JavaScript can declare any number of formal parameters. When the function is actually called, if the number of parameters passed in is less than the declared formal parameters, the value of the extra formal parameters will be undefined.

Example:


     
Copy after login

Result:

There are some things about null and undefined Interesting features:

If you use the typeof operator on a variable with a null value, the result is object;

If you use typeof on an undefined value, the result is undefined.

Such as typeof null === "object" //true; typeof undefined === "undefined" //true null == undefined //true, but null !== undefined //true

Example:


     
Copy after login

Result:

##7)、Speciality of boolean type

8), == and ===

There are two operators in JavaScript that determine whether values are equal, == and ===. Comparing the two, == will do certain type conversion; while === does not do type conversion, and the equality conditions accepted are more strict.

===The type will be compared when comparing

Of course, the corresponding ones are != and !==

Try to use === instead of ==


console.log("5"==5); //true console.log("5"===5); //false console.log("5"!=5); //false console.log("5"!==5); //true
Copy after login

2.3. Local variables and global variables

Variables declared in a function can only be used in the function. When you exit the function, the variable will be Released, such variables are called local variables. Because each local variable is only valid within its own function, you can use variables with the same name in different functions.

If you declare a variable outside a function, all functions in the page can use it. After global variables are declared, they become effective. The variable will not expire until the web page is closed.

Note: In JS language, variables declared in code blocks are global variables.

JavaScript is a language that does not have strict requirements on data type variables, so it is not necessary to declare the type of each variable. Although variable declaration is not necessary, it is good to declare it before using the variable. Habit. Variable declarations can be made using the var statement. For example: var men = true; // The value stored in men is of Boolean type.

Variable naming

JavaScript is a case-sensitive language, so naming a variable best is different from naming it Best.

In addition, the length of the variable name is arbitrary, but must follow the following rules:

  • 1. The first character must be a letter (both upper and lower case), or a An underscore (_) or a dollar sign ($).

  • 2. The subsequent characters can be letters, numbers, underscores or dollar signs.

  • 3. Variable names cannot be reserved words.

You can define variables without using var, but the variables defined in this way are global variables.

Example:


     
Copy after login

Result:

2.4, Array

①In js, array element types can be inconsistent.

②In js, the array length can be changed dynamically.

③ Following the above code, typeof arr and arr instanceof Array output object and true respectively.


console.log(typeof(names)); //object console.log(names instanceof Array); //true console.log("" instanceof String); //false 不是对象类型 console.log(true instanceof Boolean); //false
Copy after login

Array objects and methods

Array 对数组的内部支持
Array.concat( ) 连接数组
Array.join( ) 将数组元素连接起来以构建一个字符串
Array.length 数组的大小
Array.pop( ) 删除并返回数组的最后一个元素
Array.push( ) 给数组添加元素
Array.reverse( ) 颠倒数组中元素的顺序
Array.shift( ) 将元素移出数组
Array.slice( ) 返回数组的一部分
Array.sort( ) 对数组元素进行排序
Array.splice( ) 插入、删除或替换数组的元素
Array.toLocaleString( ) 把数组转换成局部字符串
Array.toString( ) 将数组转换成一个字符串
Array.unshift( ) 在数组头部插入一个元素

2.4.1、创建


var arrayObj = new Array(); var arrayObj = new Array([size]); var arrayObj = new Array([element0[, element1[, ...[, elementN]]]]);
Copy after login

示例:


var array11 = new Array(); //空数组 var array12 = new Array(5); //指定长度,可越界 var array13 = new Array("a","b","c",1,2,3,true,false); //定义并赋值 var array14=[]; //空数组,语法糖 var array15=[1,2,3,"x","y"]; //定义并赋值
Copy after login

2.4.2、访问与修改

var testGetArrValue=arrayObj[1];

arrayObj[1]= "值";


array12[8]="hello array12"; //赋值或修改 console.log(array12[8]); //取值 //遍历 for (var i = 0; i < array13.length; i++) { console.log("arrayl3["+i+"]="+array13[i]); } //枚举 for(var i in array15){ console.log(i+"="+array15[i]); //此处的i是下标 }
Copy after login

结果:

2.4.3、添加元素

将一个或多个新元素添加到数组未尾,并返回数组新长度

arrayObj. push([item1 [item2 [. . . [itemN ]]]]);

将一个或多个新元素添加到数组开始,数组中的元素自动后移,返回数组新长度

arrayObj.unshift([item1 [item2 [. . . [itemN ]]]]);

将一个或多个新元素插入到数组的指定位置,插入位置的元素自动后移,返回被删除元素数组,deleteCount要删除的元素个数

arrayObj.splice(insertPos,deleteCount,[item1[, item2[, . . . [,itemN]]]])

示例代码:


//4.3、添加元素 var array31=[5,8]; //添加到末尾 array31.push(9); var len=array31.push(10,11); console.log("长度为:"+len+"——"+array31); //添加到开始 array31.unshift(4); var len=array31.unshift(1,2,3); console.log("长度为:"+len+"——"+array31); //添加到中间 var len=array31.splice(5,1,6,7); //从第5位开始插入,删除第5位后的1个元素,返回被删除元素 console.log("被删除:"+len+"——"+array31);
Copy after login

运行结果:

2.4.4、删除

移除最后一个元素并返回该元素值

arrayObj.pop();

移除最前一个元素并返回该元素值,数组中元素自动前移

arrayObj.shift();

删除从指定位置deletePos开始的指定数量deleteCount的元素,数组形式返回所移除的元素

arrayObj.splice(deletePos,deleteCount);

示例:


//4.4、删除 var array41=[1,2,3,4,5,6,7,8]; console.log("array41:"+array41); //删除最后一个元素,并返回 var e=array41.pop(); console.log("被删除:"+e+"——"+array41); //删除首部元素,并返回 var e=array41.shift(); console.log("被删除:"+e+"——"+array41); //删除指定位置与个数 var e=array41.splice(1,4); //从索引1开始删除4个 console.log("被删除:"+e+"——"+array41);
Copy after login

结果:

2.4.5、截取和合并

以数组的形式返回数组的一部分,注意不包括 end 对应的元素,如果省略 end 将复制 start 之后的所有元素

arrayObj.slice(start, [end]);

将多个数组(也可以是字符串,或者是数组和字符串的混合)连接为一个数组,返回连接好的新的数组

arrayObj.concat([item1[, item2[, . . . [,itemN]]]]);

示例:


//4.5、截取和合并 var array51=[1,2,3,4,5,6]; var array52=[7,8,9,0,"a","b","c"]; //截取,切片 var array53=array51.slice(2); //从第3个元素开始截取到最后 console.log("被截取:"+array53+"——"+array51); var array54=array51.slice(1,4); //从第3个元素开始截取到索引号为3的元素 console.log("被截取:"+array54+"——"+array51); //合并 var array55=array51.concat(array52,["d","e"],"f","g"); console.log("合并后:"+array55);
Copy after login

结果:

2.4.6、拷贝

返回数组的拷贝数组,注意是一个新的数组,不是指向

arrayObj.slice(0);

返回数组的拷贝数组,注意是一个新的数组,不是指向

arrayObj.concat();

因为数组是引用数据类型,直接赋值并没有达到真正实现拷贝,地址引用,我们需要的是深拷贝。

2.4.7、排序

反转元素(最前的排到最后、最后的排到最前),返回数组地址

arrayObj.reverse();

对数组元素排序,返回数组地址

arrayObj.sort();

arrayObj.sort(function(obj1,obj2){});

示例:


var array71=[4,5,6,1,2,3]; array71.sort(); console.log("排序后:"+array71); var array72=[{name:"tom",age:19},{name:"jack",age:20},{name:"lucy",age:18}]; array72.sort(function(user1,user2){ return user1.age
        
Copy after login

结果:

2.4.8、合并成字符

返回字符串,这个字符串将数组的每一个元素值连接在一起,中间用 separator 隔开。

arrayObj.join(separator);

示例代码:


//4.8、合并成字符与将字符拆分成数组 var array81=[1,3,5,7,9]; var ids=array81.join(","); console.log(ids); //拆分成数组 var text="hello nodejs and angular"; var array82=text.split(" "); console.log(array82);
Copy after login

运行结果:

所有代码:


         数组操作
         
Copy after login

2.5、正则表达式RegExp

RegExp 对象表示正则表达式,它是对字符串执行模式匹配的强大工具。

RegExp对象:该对象代表正则表达式,用于字符串匹配

① 两种RegExp对象创建方式:

方式一,new 一个RegExp对象:var regExp = new RegExp(“[a-zA-Z0-9]{3,8}”);

方式二,通过字面量赋值:var regExp = /^[a-zA-Z0-9]{3,8}$/;

② 正则表达式的具体写法使用时查询文档。

③ 常用方法:test(string),返回true或false。

直接量语法

/pattern/attributes
Copy after login

创建 RegExp 对象的语法:

new RegExp(pattern, attributes);
Copy after login

参数

Parameter pattern is a string that specifies a regular expression pattern or other regular expression.

Parameter attributes is an optional string containing attributes "g", "i" and "m", which are used to specify global matching, case-sensitive matching and multi-line matching respectively. Before ECMAScript was standardized, the m attribute was not supported. If pattern is a regular expression rather than a string, this parameter must be omitted.

Return value

A new RegExp object with the specified mode and flags. If the argument pattern is a regular expression rather than a string, the RegExp() constructor creates a new RegExp object with the same pattern and flags as the specified RegExp.

If you do not use the new operator and call RegExp() as a function, its behavior is the same as when calling it with the new operator, except that when pattern is a regular expression, it only returns pattern instead of Create a new RegExp object.

Throws

SyntaxError - If pattern is not a legal regular expression, or attributes contains characters other than "g", "i" and "m", this exception is thrown.

TypeError - If pattern is a RegExp object, but the attributes parameter is not omitted, this exception is thrown.

Modifier

Modifier Description
i Perform case-insensitive matching.
g Perform global matching (find all matches instead of stopping after the first match is found).
m Perform multi-line matching.

Square brackets

Square brackets are used to find characters within a range:

Expression Description
[abc] Finds any characters between square brackets.
[^abc] Find any characters not between square brackets.
[0-9] Find any number from 0 to 9.
[a-z] Find any character from lowercase a to lowercase z.
[A-Z] Find any character from uppercase A to uppercase Z.
[A-z] Find any character from uppercase A to lowercase z.
[adgk] Find any character within the given set.
[^adgk] Find any character outside the given set.
(red|blue|green) Find any specified option.

Metacharacters

Metacharacters are characters with special meanings:

Metacharacter Description
. Finds a single character, except newlines and line terminators.
\w Find word characters.
\W Find non-word characters.
\d Find numbers.
\D Find non-numeric characters.
\s Find whitespace characters.
\S Find non-whitespace characters.
\b Matches word boundaries.
\B Matches non-word boundaries.
\0 Find NUL characters.
\n Find the newline character.
\f Find the form feed character.
\r Find the carriage return character.
\t Find the tab character.
\v Find the vertical tab character.
\xxx Find the character specified by the octal number xxx.
\xdd Search for the character specified by the hexadecimal number dd.
\uxxxx Finds the Unicode character specified as the hexadecimal number xxxx.

Quantifier

Quantifier Description
n+ Matches any string containing at least one n.
n* Matches any string containing zero or more n.
n? Matches any string containing zero or one n.
n{X} Matches a string containing X sequences of n.
n{X,Y} Matches a string containing a sequence of X to Y n.
n{X,} Matches a string containing a sequence of at least X n.
n$ Matches any string ending in n.
^n Matches any string starting with n.
?=n Matches any string immediately followed by the specified string n.
?!n Matches any string that is not immediately followed by the specified string n.

RegExp 对象属性

属性 描述 FF IE
global RegExp 对象是否具有标志 g。 1 4
ignoreCase RegExp 对象是否具有标志 i。 1 4
lastIndex 一个整数,标示开始下一次匹配的字符位置。 1 4
multiline RegExp 对象是否具有标志 m。 1 4
source 正则表达式的源文本。 1 4

RegExp 对象方法

方法 描述 FF IE
compile 编译正则表达式。 1 4
exec 检索字符串中指定的值。返回找到的值,并确定其位置。 1 4
test 检索字符串中指定的值。返回 true 或 false。 1 4

示例:


     
Copy after login

结果:

支持正则表达式的 String 对象的方法

方法 描述 FF IE
search 检索与正则表达式相匹配的值。 1 4
match 找到一个或多个正则表达式的匹配。 1 4
replace 替换与正则表达式匹配的子串。 1 4
split 把字符串分割为字符串数组。 1 4

示例:


     
Copy after login

结果:

2.6、字符串对象String

字符串是 JavaScript 的一种基本的数据类型。
String 对象的 length 属性声明了该字符串中的字符数。
String 类定义了大量操作字符串的方法,例如从字符串中提取字符或子串,或者检索字符或子串。
需要注意的是,JavaScript 的字符串是不可变的(immutable),String 类定义的方法都不能改变字符串的内容。像 String.toUpperCase() 这样的方法,返回的是全新的字符串,而不是修改原始字符串。

String 对象属性

属性 描述
constructor 对创建该对象的函数的引用
length 字符串的长度
prototype 允许您向对象添加属性和方法

String object method

Method Description
anchor() Creates an HTML anchor.
big() Display the string in large font.
blink() Display the flashing string.
bold() Use bold to display strings.
charAt() Returns the character at the specified position.
charCodeAt() Returns the Unicode encoding of the character at the specified position.
concat() Connection string.
fixed() Displays a string in typewriter text.
fontcolor() Use the specified color to display the string.
fontsize() Use the specified size to display the string.
fromCharCode() Creates a string from a character encoding.
indexOf() Retrieve string.
italics() Use italics to display strings.
lastIndexOf() Search the string from back to front.
link() Display a string as a link.
localeCompare() Compares two strings in locale-specific order.
match() Find a match for one or more regular expressions.
replace() Replace the substring matching the regular expression.
search() Retrieve values that match a regular expression.
slice() Extracts a fragment of a string and returns the extracted part in a new string.
small() Use small font size to display strings.
split() Split the string into a string array.
strike() Use strikethrough to display a string.
sub() Display the string as a subscript.
substr() Extracts the specified number of characters from the string from the starting index number.
substring() Extract the characters between two specified index numbers in the string.
sup() Display the string as superscript.
toLocaleLowerCase() Convert the string to lowercase.
toLocaleUpperCase() Convert the string to uppercase.
toLowerCase() Convert the string to lowercase.
toUpperCase() Convert the string to uppercase.
toSource() Represents the source code of the object.
toString() Returns a string.
valueOf() Returns the original value of a string object.

2.7. Time and date object Date

Date object is used to process date and time.

Syntax for creating a Date object:

var myDate=new Date();

Note: The Date object will automatically save the current date and time as its initial value.

Date object properties

Properties Description
constructor Return a reference to the Date function that created this object.
prototype Gives you the ability to add properties and methods to objects.

Date object method

Method Description
Date() Returns today's date and time.
getDate() Returns the day of the month (1 ~ 31) from the Date object.
getDay() Returns the day of the week (0 ~ 6) from the Date object.
getMonth() Returns the month (0 ~ 11) from the Date object.
getFullYear() Returns the year as a four-digit number from a Date object.
getYear() Please use getFullYear() method instead.
getHours() Returns the hours (0 ~ 23) of the Date object.
getMinutes() Returns the minutes (0 ~ 59) of the Date object.
getSeconds() Returns the number of seconds in the Date object (0 ~ 59).
getMilliseconds() Returns the milliseconds (0 ~ 999) of the Date object.
getTime() Returns the number of milliseconds since January 1, 1970.
getTimezoneOffset() Returns the difference in minutes between local time and Greenwich Mean Time (GMT).
getUTCDate() Returns the day of the month (1 ~ 31) from the Date object based on universal time.
getUTCDay() Returns the day of the week (0 ~ 6) from the Date object based on universal time.
getUTCMonth() Returns the month (0 ~ 11) from the Date object according to universal time.
getUTCFulYear() Returns the four-digit year from a Date object based on universal time.
getUTCHours() Returns the hour (0 ~ 23) of the Date object according to universal time.
getUTCMinutes() Returns the minutes (0 ~ 59) of the Date object according to universal time.
getUTCSeconds() Returns the seconds (0 ~ 59) of the Date object according to universal time.
getUTCMilliseconds() Returns the milliseconds (0 ~ 999) of the Date object according to universal time.
parse() Returns the number of milliseconds from midnight on January 1, 1970 to the specified date (string).
setDate() Set a certain day of the month (1 ~ 31) in the Date object.
setMonth() Set the month (0 ~ 11) in the Date object.
setFullYear() Set the year (four digits) in the Date object.
setYear() Please use the setFullYear() method instead.
setHours() Set the hours (0 ~ 23) in the Date object.
setMinutes() Set the minutes (0 ~ 59) in the Date object.
setSeconds() Set the seconds (0 ~ 59) in the Date object.
setMilliseconds() Set the milliseconds (0 ~ 999) in the Date object.
setTime() Sets the Date object in milliseconds.
setUTCDate() Sets the day of the month (1 ~ 31) in the Date object according to universal time.
setUTCMonth() Set the month (0 ~ 11) in the Date object according to universal time.
setUTCFulYear() Sets the year (four digits) in the Date object according to universal time.
setUTCHours() Sets the hour (0 ~ 23) in the Date object according to universal time.
setUTCMinutes() Set the minutes (0 ~ 59) in the Date object according to universal time.
setUTCSeconds() Sets the seconds (0 ~ 59) in the Date object according to universal time.
setUTCMilliseconds() Set the milliseconds (0 ~ 999) in the Date object according to universal time.
toSource() Returns the source code of the object.
toString() Convert a Date object to a string.
toTimeString() Convert the time part of the Date object to a string.
toDateString() Convert the date part of the Date object to a string.
toGMTString() Please use toUTCString() method instead.
toUTCString() Convert the Date object to a string according to universal time.
toLocaleString() Convert the Date object to a string according to the local time format.
toLocaleTimeString() Convert the time part of the Date object into a string according to the local time format.
toLocaleDateString() Convert the date part of the Date object into a string according to the local time format.
UTC() Returns the number of milliseconds from January 1, 1970 to the specified date according to universal time.
valueOf() Returns the original value of the Date object.

2.8、数学对象Math

Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math(),像 Math.sin() 这样的函数只是函数,不是某个对象的方法。您无需创建它,通过把 Math 作为对象使用就可以调用其所有属性和方法。


var pi_value=Math.PI; var sqrt_value=Math.sqrt(15);
Copy after login

Math 对象属性

属性 描述
E 返回算术常量 e,即自然对数的底数(约等于2.718)。
LN2 返回 2 的自然对数(约等于0.693)。
LN10 返回 10 的自然对数(约等于2.302)。
LOG2E 返回以 2 为底的 e 的对数(约等于 1.414)。
LOG10E 返回以 10 为底的 e 的对数(约等于0.434)。
PI 返回圆周率(约等于3.14159)。
SQRT1_2 返回返回 2 的平方根的倒数(约等于 0.707)。
SQRT2 返回 2 的平方根(约等于 1.414)。

Math 对象方法

方法 描述
abs(x) 返回数的绝对值。
acos(x) 返回数的反余弦值。
asin(x) 返回数的反正弦值。
atan(x) 以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。
atan2(y,x) 返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间)。
ceil(x) 对数进行上舍入。
cos(x) 返回数的余弦。
exp(x) 返回 e 的指数。
floor(x) 对数进行下舍入。
log(x) 返回数的自然对数(底为e)。
max(x,y) 返回 x 和 y 中的最高值。
min(x,y) 返回 x 和 y 中的最低值。
pow(x,y) 返回 x 的 y 次幂。
random() 返回 0 ~ 1 之间的随机数。
round(x) 把数四舍五入为最接近的整数。
sin(x) 返回数的正弦。
sqrt(x) 返回数的平方根。
tan(x) 返回角的正切。
toSource() 返回该对象的源代码。
valueOf() 返回 Math 对象的原始值。

2.9, JavaScript global objects

Global properties and functions can be used for all built-in JavaScript objects.

Global objects are predefined objects that serve as placeholders for JavaScript’s global functions and global properties. By using the global object, you can access all other predefined objects, functions, and properties. The global object is not a property of any object, so it has no name.
In top-level JavaScript code, you can use the keyword this to refer to the global object. But there is usually no need to reference the global object in this way, because the global object is the head of the scope chain, which means that all unqualified variable and function names will be queried as properties of the object. For example, when JavaScript code refers to the parseInt() function, it refers to the parseInt property of the global object. The global object is the head of the scope chain, which also means that all variables declared in the top-level JavaScript code will become properties of the global object.
The global object is just an object, not a class. There is neither a constructor nor the ability to instantiate a new global object.
When JavaScript code is embedded in a special environment, the global object usually has environment-specific properties. In fact, the ECMAScript standard does not specify the type of global objects. JavaScript implementations or embedded JavaScript can treat any type of object as a global object, as long as the object defines the basic properties and functions listed here. For example, in a JavaScript implementation that allows Java to be scripted via LiveConnect or related technologies, the global object is given the java and Package properties listed here and the getClass() method. In client-side JavaScript, the global object is the Window object, which represents the web browser window that allows JavaScript code.

Top-level function (global function)

Function Description
decodeURI() Decode an encoded URI.
decodeURIComponent() Decode an encoded URI component.
encodeURI() Encode a string into a URI.
encodeURIComponent() Encode a string into a URI component.
escape() Encode the string.
eval() Evaluates a JavaScript string and executes it as script code.
getClass() Returns the JavaClass of a JavaObject.
isFinite() Check whether a value is a finite number.
isNaN() Checks whether a value is a number.
Number() Convert the value of the object to a number.
parseFloat() Parse a string and return a floating point number.
parseInt() Parse a string and return an integer.
String() Convert the value of the object to a string.
unescape() Decode the string encoded by escape().

Top-level properties (global properties)

Method Description
Infinity represents a positive infinity value.
java represents a JavaPackage at the java.* package level.
NaN Indicates whether a value is a numeric value.
Packages Root JavaPackage object.
undefined Indicates an undefined value.

在 JavaScript 核心语言中,全局对象的预定义属性都是不可枚举的,所有可以用 for/in 循环列出所有隐式或显式声明的全局变量,如下所示:


var variables = ""; for (var name in this) { variables += name + "、"; } document.write(variables);
Copy after login

结果:

2.10、JavaScript避免使用的语法

1)、 ==

Javascript有两组相等运算符,一组是==和!=,另一组是===和!==。前者只比较值的相等,后者除了值以外,还比较类型是否相同。

请尽量不要使用前一组,永远只使用===和!==。因为==默认会进行类型转换,规则十分难记。如果你不相信的话,请回答下面五个判断式的值是true还是false:


false == 'false' false == undefined false == null null == undefined null == ''
Copy after login

2)、with

with的本意是减少键盘输入。比如


obj.a = obj.b; obj.c = obj.d;
Copy after login

可以简写成


with(obj) {     a = b;     c = d;   }
Copy after login

但是,在实际运行时,解释器会首先判断obj.b和obj.d是否存在,如果不存在的话,再判断全局变量b和d是否存在。这样就导致了低效率,而且可能会导致意外,因此最好不要使用with语句。

3)、eval

eval用来直接执行一个字符串。这条语句也是不应该使用的,因为它有性能和安全性的问题,并且使得代码更难阅读。

eval能够做到的事情,不用它也能做到。比如


eval("myValue = myObject." + myKey + ";");
Copy after login

可以直接写成

  myValue = myObject[myKey];

至于ajax操作返回的json字符串,可以使用官方网站提供的解析器json_parse.js运行。

4)、 continue

这条命令的作用是返回到循环的头部,但是循环本来就会返回到头部。所以通过适当的构造,完全可以避免使用这条命令,使得效率得到改善。

5)、switch 贯穿

switch结构中的case语句,默认是顺序执行,除非遇到break,return和throw。有的程序员喜欢利用这个特点,比如


switch(n) {     case 1:     case 2:       break;   }
Copy after login

这样写容易出错,而且难以发现。因此建议避免switch贯穿,凡是有case的地方,一律加上break。


switch(n) {     case 1:       break;     case 2:       break;   }
Copy after login

6)、单行的块结构

if、while、do和for,都是块结构语句,但是也可以接受单行命令。比如

  if (ok) t = true;

甚至写成

  if (ok)
    t = true;
这样不利于阅读代码,而且将来添加语句时非常容易出错。建议不管是否只有一行命令,都一律加上大括号。

  if (ok){
    t = true;
  }

7)、 ++和--

递增运算符++和递减运算符--,直接来自C语言,表面上可以让代码变得很紧凑,但是实际上会让代码看上去更复杂和更晦涩。因此为了代码的整洁性和易读性,不用为好。

8)、位运算符

Javascript完全套用了Java的位运算符,包括按位与&、按位或|、按位异或^、按位非~、左移<<、带符号的右移>>和用0补足的右移>>>。

这套运算符针对的是整数,所以对Javascript完全无用,因为Javascript内部,所有数字都保存为双精度浮点数。如果使用它们的话,Javascript不得不将运算数先转为整数,然后再进行运算,这样就降低了速度。而且"按位与运算符"&同"逻辑与运算符"&&,很容易混淆。

9)、function语句

在Javascript中定义一个函数,有两种写法:

  function foo() { }

  var foo = function () { }
两种写法完全等价。但是在解析的时候,前一种写法会被解析器自动提升到代码的头部,因此违背了函数应该先定义后使用的要求,所以建议定义函数时,全部采用后一种写法。

10)、基本数据类型的包装对象

Javascript的基本数据类型包括字符串、数字、布尔值,它们都有对应的包装对象String、Number和Boolean。所以,有人会这样定义相关值:


  new String("Hello World");   new Number(2000);   new Boolean(false);
Copy after login

这样写完全没有必要,而且非常费解,因此建议不要使用。

另外,new Object和new Array也不建议使用,可以用{}和[]代替。

11)、new语句

Javascript是世界上第一个被大量使用的支持Lambda函数的语言,本质上属于与Lisp同类的函数式编程语言。但是当前世界,90%以上的程序员都是使用面向对象编程。为了靠近主流,Javascript做出了妥协,采纳了类的概念,允许根据类生成对象。

类是这样定义的:


  var Cat = function (name) {     this.name = name;     this.saying = 'meow' ;   }
Copy after login

然后,再生成一个对象

var myCat = new Cat('mimi');
这种利用函数生成类、利用new生成对象的语法,其实非常奇怪,一点都不符合直觉。而且,使用的时候,很容易忘记加上new,就会变成执行函数,然后莫名其妙多出几个全局变量。所以,建议不要这样创建对象,而采用一种变通方法。

Douglas Crockford给出了一个函数:


Object.beget = function (o) {     var F = function (o) {};     F.prototype = o ;     return new F;   };
Copy after login

创建对象时就利用这个函数,对原型对象进行操作:


var Cat = {     name:'',     saying:'meow'   };   var myCat = Object.beget(Cat);
Copy after login

对象生成后,可以自行对相关属性进行赋值:

  myCat.name = 'mimi';

12)、void

在大多数语言中,void都是一种类型,表示没有值。但是在Javascript中,void是一个运算符,接受一个运算数,并返回undefined。

 void 0; // undefined
这个命令没什么用,而且很令人困惑,建议避免使用。

三、BOM

3.1、BOM概要

BOM(Browser Object Model) 即浏览器对象模型,主要是指一些浏览器内置对象如:window、location、navigator、screen、history等对象,用于完成一些操作浏览器的特定API。

用于描述这种对象与对象之间层次关系的模型,浏览器对象模型提供了独立于内容的、可以与浏览器窗口进行互动的对象结构。BOM由多个对象组成,其中代表浏览器窗口的Window对象是BOM的顶层对象,其他对象都是该对象的子对象。

  • BOM是browser object model的缩写,简称浏览器对象模型

  • BOM提供了独立于内容而与浏览器窗口进行交互的对象

  • 由于BOM主要用于管理窗口与窗口之间的通讯,因此其核心对象是window

  • BOM由一系列相关的对象构成,并且每个对象都提供了很多方法与属性

  • BOM缺乏标准,JavaScript语法的标准化组织是ECMA,DOM的标准化组织是W3C

  • BOM最初是Netscape浏览器标准的一部分

BOM结构

从上图可以看出:DOM是属于BOM的一个属性。

window对象是BOM的顶层(核心)对象,所有对象都是通过它延伸出来的,也可以称为window的子对象。

由于window是顶层对象,因此调用它的子对象时可以不显示的指明window对象。

以下两种写法均可:


document.write("www.jb51.net"); window.document.write(www.jb51.net);
Copy after login

3.2、BOM导图

BOM部分主要是针对浏览器的内容,其中常用的就是window对象和location

window是全局对象很多关于浏览器的脚本设置都是通过它。

location则是与地址栏内容相关,比如想要跳转到某个页面,或者通过URL获取一定的内容。

navigator中有很多浏览器相关的内容,通常判断浏览器类型都是通过这个对象。

screen常常用来判断屏幕的高度宽度等。

history访问浏览器的历史记录,如前进、后台、跳转到指定位置。

3.3、window对象

window对象在浏览器中具有双重角色:它既是ECMAscript规定的全局global对象,又是javascript访问浏览器窗口的一个接口。


moveBy() 函数 moveTo() 函数 resizeBy() 函数 resizeTo() 函数 scrollTo() 函数 scrollBy() 函数 focus() 函数 blur() 函数 open() 函数 close() 函数 opener 属性 alert() 函数 confirm() 函数 prompt() 函数 defaultStatus 属性 status 属性 setTimeout() 函数 clearTimeout() 函数 setInterval() 函数 clearInterval() 函数
Copy after login

1、获取窗口相对于屏幕左上角的位置


window.onresize = function() { var leftPos = (typeof window.screenLeft === 'number') ? window.screenLeft : window.screenX; var topPos = (typeof window.screenLeft === 'number') ? window.screenTop : window. screenY; document.write(leftPos+","+topPos); console.log(leftPos+","+topPos); }
Copy after login

需要注意的一点是,在IE,opera中,screenTop保存的是页面可见区域距离屏幕左侧的距离,而chrome,firefox,safari中,screenTop/screenY保存的则是整个浏览器区域距离屏幕左侧的距离。也就是说,二者差了一个浏览器工具栏的像素高度。

2、移动窗口,调整窗口大小


window.moveTo(0,0) window.moveBy(20,10) window.resizeTo(100,100); window.resizeBy(100,100);
Copy after login

注意,这几个方法在浏览器中很可能会被禁用。

3、获得浏览器页面视口的大小


var pageWith=document.documentElement.clientWidth||document.body.clientWidth; var pageHeight=document.documentElement.clientHeight||document.body.clientHeight;
Copy after login

4、导航和打开窗口

window.open()既可以导航到特定的URL,也可以打开一个新的浏览器窗口,其接收四个参数,要加载的url,窗口目标(可以是关键字_self,_parent,_top,_blank),一个特性字符串,以及一个表示新页面是否取代浏览器历史记录中当前加载页面的布尔值。通常只需要传递第一个参数。注意,在很多浏览器中,都是阻止弹出窗口的。

5、定时器

setTimeout(code,millisec)

setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式。

code 必需,要调用的函数后要执行的 JavaScript 代码串。=

millisec 必需,在执行代码前需等待的毫秒数。

clearTimeout(对象) 清除已设置的setTimeout对象

示例:


     
Copy after login

结果:

setInterval(code,millisec[,"lang"])

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式
code 必需,要调用的函数或要执行的代码串。

millisec 必需,周期性执行或调用code之间的时间间隔,以毫秒计。

clearInterval(对象) 清除已设置的setInterval对象

6.系统对话框,这些对话框外观由操作系统/浏览器设置决定,css不起作用,所以很多时候可能需要自定义对话框

alert():带有一个确定按钮

confirm():带有一个确定和取消按钮

prompt():显示OK和Cancel按钮之外,还会显示一个文本输入域

示例:


     
Copy after login

结果:

6、scroll系列方法

scrollHeight和scrollWidth 对象内部的实际内容的高度/宽度(不包括border)

scrollTop和scrollLeft 被卷去部分的顶部/左侧 到 可视区域 顶部/左侧 的距离

onscroll事件 滚动条滚动触发的事件

页面滚动坐标:

var scrollTop = window.pageYoffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

3.4、document 对象

请参考DOM一节的内容

write() 函数
writeln() 函数
document.open() 函数
document.close() 函数

3.5、location对象

location对象提供了当前窗口加载的文档的相关信息,还提供了一些导航功能。事实上,这是一个很特殊的对象,location既是window对象的属性,又是document对象的属性。

location.hash  #contents  返回url中的hash,如果不包含#后面的内容,则返回空字符串

location.host  best.cnblogs.com:80  返回服务器名称和端口号

location.port  80  返回端口号

location.hostname  best.cnblogs.com  返回服务器名称

location.href  http://best.cnblogs.com  返回当前加载页面的完整url

location.pathname  /index.html  返回url中的目录和文件名

location.protocol http  返回页面使用的协议

location.search  ?q=javascript  返回url中的查询字符串

改变浏览器的位置:location.href=http://www.baidu.com

如果使用location.replace('http://www.baidu.com'),不会在历史记录中生成新纪录,用户不能回到前一个页面。

location.reload():重置当前页面,可能从缓存,也可能从服务器;如果强制从服务器取得,传入true参数

示例:


     
Copy after login

结果:

3.6、history对象

history对象保存着用户上网的历史记录,使用go()实现在用户的浏览记录中跳转:


history.go(-1) 等价于history.back() history.go(1) 等价于 history.forward() history.go(1) //前进两页 history.go('jb51.net')
Copy after login

3.7、navigator对象

这个对象代表浏览器实例,其属性很多,但常用的不太多。如下:

navigator.userAgent:用户代理字符串,用于浏览器监测中、

navigator.plugins:浏览器插件数组,用于插件监测

navigator.registerContentHandler 注册处理程序,如提供RSS阅读器等在线处理程序。

示例代码:


    Title 
Copy after login

运行结果:


/* 浏览器名称Mozilla 次版本信息undefined 完整的浏览器名称Netscape 浏览器版本5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36 浏览器编译版本undefined 是否启用cookietrue 客户端计算机CPU类型undefined 浏览器是否启用javafalse 浏览器主语言zh-CN 浏览器中注册的MIME类型数组[object MimeTypeArray] 是否连接到网络true 客户端计算机操作系统或者CPUundefined 浏览器所在的系统平台Win32 浏览器中插件信息数组[object PluginArray] 用户的首选项 产品名称Gecko 产品的次要信息20030107 操作系统的语言undefined 浏览器的用户代理字符串Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36 操作系统默认语言undefined 用户个人信息对象undefined 浏览器品牌Google Inc. 浏览器供应商次要信息 */
Copy after login

四、DOM

DOM(文档对象模型)是针对HTML和XML文档的一个API,通过DOM可以去改变文档。

DOM模型将整个文档(XML文档和HTML文档)看成一个树形结构,并用document对象表示该文档。

DOM规定文档中的每个成分都是一个节点(Node):

文档节点(Document):代表整个文档
元素节点(Element):文档中的一个标记
文本节点(Text):标记中的文本
属性节点(Attr):代表一个属性,元素才有属性

4.1、节点类型

12中节点类型都有NodeType属性来表明节点类型

节点类型 描述
1 Element 代表元素
2 Attr 代表属性
3 Text 代表元素或属性中的文本内容。
4 CDATASection 代表文档中的 CDATA 部分(不会由解析器解析的文本)。
5 EntityReference 代表实体引用。
6 Entity 代表实体。
7 ProcessingInstruction 代表处理指令。
8 Comment 代表注释。
9 Document 代表整个文档(DOM 树的根节点)。
10 DocumentType 向为文档定义的实体提供接口
11 DocumentFragment 代表轻量级的 Document 对象,能够容纳文档的某个部分
12 Notation 代表 DTD 中声明的符号。

示例:


    DOM 

Copy after login

结果:

4.2、节点关系

nodeType 返回节点类型的数字值(1~12)
nodeName 元素节点:标签名称(大写)、属性节点:属性名称、文本节点:#text、文档节点:#document
nodeValue 文本节点:包含文本、属性节点:包含属性、元素节点和文档节点:null
parentNode 父节点
parentElement 父节点标签元素
childNodes 所有子节点
children 第一层子节点
firstChild 第一个子节点,Node 对象形式
firstElementChild 第一个子标签元素
lastChild 最后一个子节点
lastElementChild 最后一个子标签元素
previousSibling 上一个兄弟节点
previousElementSibling 上一个兄弟标签元素
nextSibling 下一个兄弟节点
nextElementSibling 下一个兄弟标签元素
childElementCount 第一层子元素的个数(不包括文本节点和注释)
ownerDocument 指向整个文档的文档节点

节点关系方法:

hasChildNodes() 包含一个或多个节点时返回true
contains() 如果是后代节点返回true
isSameNode()、isEqualNode() 传入节点与引用节点的引用为同一个对象返回true
compareDocumentPostion() 确定节点之间的各种关系

示例:


    DOM 

p1

p2

p3

Copy after login

结果:

4.3、选择器

getElementById()

一个参数:元素标签的ID
getElementsByTagName() 一个参数:元素标签名
getElementsByName() 一个参数:name属性名
getElementsByClassName() 一个参数:包含一个或多个类名的字符串

classList

返回所有类名的数组

  • add (添加)

  • contains (存在返回true,否则返回false)

  • remove(删除)

  • toggle(存在则删除,否则添加)

querySelector() 接收CSS选择符,返回匹配到的第一个元素,没有则null
querySelectorAll() 接收CSS选择符,返回一个数组,没有则返回[]

示例:


    DOM  

p1

p2

p3

Copy after login

结果:

4.4、样式操作方法style

style.cssText 可对style中的代码进行读写
style.item() 返回给定位置的CSS属性的名称
style.length style代码块中参数个数
style.getPropertyValue() 返回给定属性的字符串值
style.getPropertyPriority() 检测给定属性是否设置了!important,设置了返回"important";否则返回空字符串
style.removeProperty() 删除指定属性
style.setProperty() 设置属性,可三个参数:设置属性名,设置属性值,是否设置为"important"(可不写或写"")

代码:


    DOM  

p1

p2

p3

Copy after login

结果:

4.5、元素节点ELEMENT

nodeName 访问元素的标签名
tagName 访问元素的标签名
createElement() 创建节点
appendChild() 末尾添加节点,并返回新增节点
insertBefore() 参照节点之前插入节点,两个参数:要插入的节点和参照节点
insertAfter() 参照节点之后插入节点,两个参数:要插入的节点和参照节点
replaceChild() 替换节点,两个参数:要插入的节点和要替换的节点(被移除)
removeChild() 移除节点
cloneNode() 克隆,一个布尔值参数,true为深拷贝,false为浅拷贝
importNode() 从文档中复制一个节点,两个参数:要复制的节点和布尔值(是否复制子节点)
insertAdjacentHTML()

插入文本,两个参数:插入的位置和要插入文本

  • "beforebegin",在该元素前插入

  • "afterbegin",在该元素第一个子元素前插入

  • "beforeend",在该元素最后一个子元素后面插入

  • "afterend",在该元素后插入

示例:


    DOM 
Copy after login

结果:

4.6、属性节点attributes

attributes

获取所有标签属性
getAttribute() 获取指定标签属性
setAttribute() 设置指定标签属
removeAttribute() 移除指定标签属

var s = document.createAttribute("age")

s.nodeValue = "18"

创建age属性

设置属性值为18

示例:


    DOM 
Copy after login

结果:

4.7、文本节点TEXT

innerText 所有的纯文本内容,包括子标签中的文本
outerText 与innerText类似
innerHTML 所有子节点(包括元素、注释和文本节点)
outerHTML 返回自身节点与所有子节点
textContent 与innerText类似,返回的内容带样式
data 文本内容
length 文本长度
createTextNode() 创建文本
normalize() 删除文本与文本之间的空白
splitText() 分割
appendData() 追加
deleteData(offset,count) 从offset指定的位置开始删除count个字符
insertData(offset,text) 在offset指定的位置插入text
replaceData(offset,count,text) 替换,从offset开始到offscount处的文本被text替换
substringData(offset,count) 提取从ffset开始到offscount处的文本

4.8、文档节点 Document

document.documentElement 代表页面中的元素
document.body 代表页面中的元素
document.doctype 代表标签
document.head 代表页面中的元素
document.title 代表元素的文本,可修改</td></tr>
document.URL 当前页面的URL地址
document.domain 当前页面的域名
document.charset 当前页面使用的字符集
document.defaultView 返回当前 document对象所关联的 window 对象,没有返回 null
document.anchors 文档中所有带name属性的元素
document.links 文档中所有带href属性的元素
document.forms 文档中所有的
元素
document.images 文档中所有的元素
document.readyState 两个值:loading(正在加载文档)、complete(已经加载完文档)
document.compatMode

两个值:BackCompat:标准兼容模式关闭、CSS1Compat:标准兼容模式开启

write()、writeln()、

open()、close()

write()文本原样输出到屏幕、writeln()输出后加换行符、

open()清空内容并打开新文档、close()关闭当前文档,下次写是新文档

示例:


    DOM 
Copy after login

结果:

五、学习资料

http://common.jb51.net/tag/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3JavaScript%E7%B3%BB%E5%88%97/1.htm

六、作业

6.1)、尽量多的输出javascript中为false的情况

6.2)、尽量多的输出javascript中为undefined的情况

6.3)、用示例说明未定义全局变量,特别是没有使用var关键字时

6.4)、请定对照“数组”一节的内容,练习数组定义与每一个已列出的数组方法

6.5)、请使用纯JavaScript(不允许使用任何三方库,如jQuery)完成下列功能:

要求:

全选、反选、子项全部选项时父项被选择
完成所有功能
鼠标移动到每一行上时高亮显示(js)
尽量使用弹出窗口完成增加、修改、详细功能
删除时提示
使用正则验证
封装代码,最终运行的代码只有一个对象,只对外暴露一个对象
越漂亮越好

6.6)、请写出以下两个正则表达式并使用两个文本框模拟用户提交数据时验证:

//身份证
//411081199004235955 41108119900423595x 41108119900423595X
//邮箱
//zhangguo123@qq.com zhangguo@sina.com.cn

6.7)、请写一个javascript方法getQuery(key)用于根据key获得url中的参值,如果不指定参数则返回一个数组返回所有参数,如:


url: http://127.0.0.1?id=1&name=tom getQuery("id") 返回 1 getQuery() 返回[{key:id,value:1},{key:name,value:tom}] //思考一个如果有多个想同的key时怎样处理
Copy after login

相关推荐:

JavaScript基础进阶之数组相关介绍

JavaScript基础知识点学习总结

详解9个JavaScript图表库

最全JavaScript的模块讲解

JavaScript队列原理与用法实例详解

The above is the detailed content of The most complete JavaScript learning summary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!