JavaScript一站式入门笔记

封面


大二开始接触的javascript,到现在,五年过去了,中间断断续续用了一些,但是主要是搞后端的,没有正儿八经“学习”一下。

对其了解不成系统,最近做了一个系统涉及前端框架,所以借此机会学习总结了下。

入门笔记,非初学者可以绕道哈:)

后续打算深入学习一下,顺带去玩玩node.js


参考教程

入门: 【已完成】

进阶:【待阅读】

其他资料

书籍

  • javascript 权威指南

注意:笔记全部来自于以上资料

目录

 第一部分:简介(Getting Started)
  1.HTML/CSS/JavaScript
  2.JavaScript书写和位置
  3.简单语法
 第二部分:基本语法
  1.变量(varivalbes)
  2.操作符(operators)
  3.真值判断 - 比较
  4.控制流
    分支
    循环
 第二部分:函数
  1.Functions
  2.global functions
 第三部分:对象
  1.Array
  2.Object
 第四部分:内置对象
  1.字符串(string)
  2.math
  3.date
  4.boolean
 第五部分: DOM 操作
 第六部分:其他
  1.正则
  2.this关键字
  3.异常处理
  4.作用域
    Global Scope
    Local Scope
  5.闭包
  6.typeof(Testing Type)
  7.Timers

第一部分:简介(Getting Started)

1.HTML/CSS/JavaScript

关系

HTML is for Content
CSS is for Presentation
JavaScript is for Interactivity

2.JavaScript书写和位置

external,外部js文件引入

<!-- Code is written in a .js file, included via the script tag src attribute. -->
<script src="/path/to/example.js"></script>

inline,本页面

<!-- Embed code directly on a web page using script tags. -->
<script type="text/javascript">
alert( "Hello World!" );
</script>

attribute

<!-- Inline code directly on HTML elements being clicked. -->
<a href="javascript:alert( 'Hello World' );">Click Me!</a>
<button onClick="alert( 'Good Bye World' );">Click Me Too!</button>

BP:将<script>放到页面底部,<body>标签之前

<!doctype html>
<html>
<head></head>
<body>

<h1 id="hello-world">Hello World</h1>
<script>
// Moving the script to the bottom of the page will make sure the element exists.
var title = document.getElementById( "hello-world" );
console.log( title );
</script>
</body>
</html>

3.简单语法

code sample

var hello = "Hello";
var world = "World";

// Message equals "Hello World"
var message = hello + " " + world;

分号 ;

分号用于分隔 JavaScript 语句。
通常我们在每条可执行的语句结尾添加分号。
使用分号的另一用处是在一行中编写多条语句。

注释

// 单行,This is a comment, it will be ignored by the interpreter
var a = "this is a variable defined in a statement";

/*
多行
This is a multi-line comment,
it will be ignored by the interpreter
*/
var a = "this is a variable defined in a statement";

对代码行进行折行 - 可以对js代码通过反斜杠,拆分换行

JavaScript 会忽略多余的空格。可以向脚本添加空格,来提高其可读性。(空格和折行无关紧要)

javaScript 中的所有事物都是对象:字符串、数字、数组、日期,等等。


第二部分:基本语法

1.变量(varivalbes)

命名

必须以字母开头, 也能以 $ 和 _ 符号开头(不过我们不推荐这么做)
可以包含数字
名称大小写敏感(y 和 Y 是不同的变量)
不能使用保留字

注意:变量命名不要使用保留字 Reserved Words

声明和赋值

var age;
age = 26;
//or
var age = 26;

var age, height, weight, gender;
//or
var name="Gates", age=56, job="CEO";

//注意,只声明不赋值,其值为undefined
var x;
x === undefined; // true

//=================

// This works:
var test = 1;
var test2 = function() { ... };
var test3 = test2( test );

// And so does this:
var test4 = 1,
    test5 = function() { ... },
    test6 = test2( test );

变量类型 Types

Numbers
    Float: a number, like 1.21323, 4, -33.5, 100004 or 0.123
    Integer: a number like 1, 12, -33, 140 but not 1.233
String: a line of text like "boat", "elephant" or "damn, you are tall!"
Boolean: either true or false, but nothing else
    // Boolean values.
    var okay = true;
    var fail = false;
Arrays: a collection of values like: 1,2,3,4,'I am bored now'
Objects: a representation of a more complex object

null
    // Define a null value. 可用于清空变量
    var foo = null;
undefined, 表示变量不含值
    // Two ways to achieve an undefined value.
    var bar1 = undefined;
    var bar2;

2.操作符(operators)

算术(Arithmetic Operators)

Operator Description
+        Addition
-        Subtraction
*        Multiplication
/        Division
%        Modulus (remainder)
++       Increment by one
--       Decrement by one

Increment: Given a = 5
    c = a++, Results: c = 5 and a = 6
    c = ++a, Results: c = 6 and a = 6
Decrement: Given a = 5
    c = a--, Results: c = 5 and a = 4
    c = --a, Results: c = 4 and a = 4

注意

减法(-)
将两边的操作数都转换为数字

加法(+)
1. 两边的操作数首先被转换成原始值.这里我们称之为A 和 B.
2. 如果有任意一个原始值是字符串,则把另一个也转换成字符串,执行A和B的连接操作并返回连接后的字符串.
3. 否则把A和B都转换为数字,返回两个数字的和

< 同 +

赋值操作符(Assignment Operators)

Operator    Description
=           Assignment, a = 3
+=          (a+=3 is the same as a=a+3)
-=          (a-=3 is the same as a=a-3)
*=          (a*=3 is the same as a=a*3)
/=          (a/=3 is the same as a=a/3)
%=          (a%=3 is the same as a=a%3)

字符串操作符(String Operators)

Operator    Description
+           Concatenation (var greeting = "Hello " + firstname;)
+=          One step concatenation and assignment (var greeting = "Hello "; greeting += firstname;)

"hello".concat(" world")// "hello world"

注意区别
// Addition vs. Concatenation
var foo = 1;
var bar = "2";
console.log( foo + bar ); // 12

// Coercing a string to act as a number.
var foo = 1;
var bar = "2";

console.log( foo + Number(bar) ); // 3

三元运算(Ternary Operator)

test ? expression1 : expression2

test
任何 Boolean 表达式。
expression1
如果 test 为 true,则返回表达式。 可能是逗号表达式。
expression2
如果 test 为 false,则返回表达式。 可以使用逗号表达式链接多个表达式。

e.g.
// Set foo to 1 if bar is true; otherwise, set foo to 0:
var foo = bar ? 1 : 0;

默认值(Default Operator)

Operator    Description
||          Used to assign a default operator

var yourName = prompt("Your Name?","") || "Stranger";

比较运算符(Comparison operators)

==  Equals
!=  Doesn't equal
=== Strictly equals
!== Doesn't strictly equal
>   Is greater than
<   Is less than
>=  Is greater than or equal to
<=  Is less than or equal to

== / === 的区别
== 值相等, === 值相等,且类型相同

BP: 相等比较总是使用 === 和 !===

//=====================

e.g.
var foo = 1;
var bar = 0;
var baz = "1";
var bim = 2;

foo == bar; // false
foo != bar; // true
foo == baz; // true; but note that the types are different

foo === baz;             // false
foo !== baz;             // true
foo === parseInt( baz ); // true

foo > bim;  // false
bim > baz;  // true
foo <= baz; // true

3.真值判断 - 比较

真值判断

// Values that evaluate to false:

false
"" // An empty string.
NaN // JavaScript's "not-a-number" variable.
null
undefined // Be careful -- undefined can be redefined!
0 // The number zero.

// Values that evaluate to true:

true
// Everything else evaluates to true, some examples:
"0"
"any string"
[] // An empty array.
{} // An empty object.
1 // Any non-zero number.

逻辑运算

//短路运算
&&  and (a == b && c != d)
||  or (a == b || c != d)
!   not !(a == b || c != d)

--------------------

// Logical AND and OR operators

var foo = 1;
var bar = 0;
var baz = 2;

// returns 1, which is true
foo || bar;

// returns 1, which is true
bar || foo;

// returns 0, which is false
foo && bar;

// returns 2, which is true
foo && baz;

// returns 1, which is true
baz && foo;

--------------------

if(x > 10 && x < 20) {
    ...
}

if(country === 'England' || country === 'Germany') {
        ...
}


if ( (name === "John" || name === "Jennifer") && country === "France")

--------------------

//其他用法
// Do something with foo if foo is truthy.
foo && doSomething( foo );

// Set bar to baz if baz is truthy;
// otherwise, set it to the return value of createBar()
var bar = baz || createBar();

4.控制流

分支

if-eles

if (conditions) {
    statements;
} else if (conditions) {
    statements;
} else {
    statements;
}

e.g.

if (time<10)
{
    x="Good morning";
} else if (time<20)
{
    x="Good day";
} else
{
    x="Good evening";
}

switch

在判断情况大于2种的时候,使用 switch/case 更高效,而且更优雅(更易于组织代码)。但在判断的情况超过10种的时候不要使用 switch/case

switch (expression) {
    case value :
        statements;
    case value :
        statements;
    default :
        statements;
}

e.g.

//记得break
var quantity = 1;
switch (quantity) {
    case 1 :
        alert("quantity is 1");
        break;
    case 2 :
        alert("quantity is 2");
        break;
    default :
        alert("quantity is not 1 or 2");
}

循环

for

for (initialization; conditions; change) {
    statements;
}

e.g.

for(var i = 0; i < 10; i = i + 1){
    // do this code ten-times
}

var i = 0;
for(; i<length; i+=2) {
}

var i=0,len=cars.length;
for (; i<len; )
{
    document.write(cars[i] + "<br>");
    i++;
}

for/in

谨慎使用for-in, 遍历一个对象中的成员(属性,方法),如果用来遍历数组的到的结果并不是预期中数组每项的值,方法神马的会被遍历出来

for (var index in array) {
    statements;
    //array[index]
}

for (var key in object) {
    statements;
    //object[key]
}
for (var name in object) {
    if (object.hasOwnProperty(name)) {
        // do something with name
    }
}

e.g.

while

while (conditions) {
    statements;
}

e.g.

var i = 0, x = "";
while (i < 5) {
    x = x + "The number is " + i;
    i++;
}

do-while

do {
    statements;
} while (conditions);

e.g.

do {
    // Even though the condition evaluates to false
    // this loop's body will still execute once.
    alert( "Hi there!" );
} while ( false );

break/continue

break 语句用于跳出循环。
continue 用于跳过循环中的一个迭代。

label:
    语句

break labelname;
continue labelname;

e.g.

// Stopping a loop
for ( var i = 0; i < 10; i++ ) {
    if ( something ) {
        break;
    }
}

// Skipping to the next iteration of a loop
for ( var i = 0; i < 10; i++ ) {
    if ( something ) {
        continue;
    }
    // The following statement will only be executed
    // if the conditional "something" has not been met
    console.log( "I have been reached" );

}

第二部分:函数

1.Functions

声明

// Function declaration.
function foo() {
    // Do something.
}

// Named function expression.
var foo = function() {
    // Do something.
};

function myFunction(var1,var2)
{
    //function statements go here
}

e.g.

function double(x) {
    return 2 * x;
}

or

var double = function(x) {
    return 2 * x;
};

参数

function changeBg(color){
    document.bgColor = color;
}

返回值

function myFunction()
{
    var x=5;
    return x;
}
var myVar=myFunction();

e.g.

// A simple function.
var greet = function( person, greeting ) {
    var text = greeting + ", " + person;
    console.log( text );
};

greet( "Rebecca", "Hello" ); // "Hello, Rebecca"


// A function that returns a value.
var greet = function( person, greeting ) {
    var text = greeting + ", " + person;
    return text;
};

console.log( greet( "Rebecca", "Hello" ) ); // "Hello, Rebecca"


// A function that returns another function.
var greet = function( person, greeting ) {
    var text = greeting + ", " + person;
    return function() {
        console.log( text );
    };
};

var greeting = greet( "Rebecca", "Hello" );

greeting(); // "Hello, Rebecca"

Immediately-Invoked Function Expression (IIFE)

参阅文章 IIFE

创建并立刻执行.This pattern is extremely useful for cases where you want to avoid polluting the global namespace with code – no variables declared inside of the function are visible outside of it.

// An immediately-invoked function expression.

(function() {
    var foo = "Hello world";
})();

console.log( foo ); // undefined!

方法作为参数

方法可以赋值给变量,且,可以作为函数参数传递

// Passing an anonymous function as an argument.
var myFn = function( fn ) {
    var result = fn();
    console.log( result );
};

// Logs "hello world"
myFn( function() {
    return "hello world";
});

// Passing a named function as an argument
var myFn = function( fn ) {
    var result = fn();
    console.log( result );
};

var myOtherFn = function() {
    return "hello world";
};

myFn( myOtherFn ); // "hello world"

2.global functions

These “global” functions we have discussed above are actually methods of the window object, but as window is assumed if no object is referenced, we don’t need to explicitly write window.parseFloat() or window.isNaN(). Also, some of these functions such as Number() and String() are really function constructors for creating new String and Number objects. For now, just remember that you can use these functions to ensure you are working with a String or Number.

  • Number(object)

一个数值包装器

Number的属性

MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
POSITIVE_INFINITY

方法

toExponential ,  toExponential 方法以指数形式返回 数字的字符串表示
toFixed, 四舍五入
toPrecision
toString
valueOf, valueOf 方法返回调用它的对象类型的原始

转为数字,如果失败返回NaN(Not a Number)

var strNum1 = "1";
var strNum2 = "2";
var strSum = strNum1 + strNum2; //returns 12
alert(strSum);

var intNum1 = Number(strNum1);
var intNum2 = Number(strNum2);
var intSum = intNum1 + intNum2; //returns 3
alert(intSum);

// 四舍五入一个数字,保留N位小数
var num =2.443242342;
num = num.toFixed(4);  // num will be equal to 2.4432
  • Boolean(object)

Boolean 是一个 代表 true 或 false 值的对象

Boolean 对象有多个值,这些值

相当于 false 值(0、 -0、null 或 “” [一个空字串]),未定义的 (NaN),当然还有 false。
所有其他布尔 值相当于 true 值

var myBoolean = true; if(myBoolean == true) { // If the condition evaluates to true } else { // If the condition evaluates to false }

  • String(object)

转为字符串

var intNum1 = 1;
var intNum2 = 2;
var intSum = intNum1 + intNum2; //returns 3
alert(intSum);

var strNum1 = String(intNum1);
var strNum2 = String(intNum2);
var strSum = strNum1 + strNum2; //returns 12
alert(strSum);

具体见string 方法

isNaN(object)

判断是否为数字,或者是否可以被转为数字。如果是数字,return false,否则,return true;

isNaN(4) //false
isNaN('4') //false

isNaN('hello') //true
isNaN(0/0) //true

parseFloat() and parseInt()

The parseFloat() 如果字符串以数字开头,将会将字符串开头数字部分转为数字。否则,返回NaN

The parseInt() 如果字符串以数字开头,将会将字符串开头数字部分转为数字。否则,返回NaN

parseInt(string, radix), radix=[2,36], radix不设or0, 根据string, “0x”16进制, “0"8进制

var race = "26.2 miles";
parseFloat(race); //26.2
parseInt(race);  //26

race = "Marathon";
parseFloat(race); //NaN
parseInt(race); //NaN

第三部分:对象

1.Array

声明

//语法
new Array();
new Array(size);
new Array(element0, element1, ..., elementn);

// Creating an array with the constructor:
var myarray = new Array();

// Creating an array with the array literal syntax:
var bar = [];

========================

// A simple array with constructor.
var myArray1 = new Array( "hello", "world" );

// Literal declaration, the preferred way.
var myArray2 = [ "hello", "world" ];

========================

var bar = new Array( 100 );
alert( bar[ 0 ] ); // undefined
alert( bar.length ); // 100

var foo = [ 100 ];
alert( foo[ 0 ] ); // 100
alert( foo.length ); // 1

a = new Array(3) // [undefined × 3]
a[0] // undefined

赋值

var myArray = [];

myArray[ 0 ] = "hello";
myArray[ 1 ] = "world";
myArray[ 3 ] = "!";

//Missing indices will be filled with undefined.
console.log( myArray ); // [ "hello", "world", undefined, "!" ];

读取

// Accessing array items by index
var myArray = [ "hello", "world", "!" ];
console.log( myArray[ 2 ] ); // "!"

属性-length

// Length of an array
var myArray = [ "hello", "world", "!" ];
console.log( myArray.length ); // 3

原生数组函数

遍历

// For loops and arrays - a classic
var myArray = [ "hello", "world", "!" ];
for ( var i = 0; i < myArray.length; i = i + 1 ) {
    console.log( myArray[ i ] );
}

// for/in
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"

for (x in mycars)
{
    console.log(mycars[x]);
}

常用方法

方法-push/pop

// Pushing and popping

var myArray = [];

myArray.push( 0 ); // [ 0 ]
myArray.push( 2 ); // [ 0 , 2 ]
myArray.push( 7 ); // [ 0 , 2 , 7 ]
b = myArray.pop();     // [ 0 , 2 ] , b=7

方法-concat

var myArray = [ 2, 3, 4 ];
var myOtherArray = [ 5, 6, 7 ];
// 返回新数组
var wholeArray = myArray.concat( myOtherArray ); // [ 2, 3, 4, 5, 6, 7 ]

//附加(append)一个数组到另一个数组上
var array1 = [12 , "foo" , {name: "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];

Array.prototype.push.apply(array1, array2);
/* array1 will be equal to  [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */

方法-join

// Joining elements
var myArray = [ "hello", "world", "!" ];

// The default separator is a comma. 默认逗号
console.log( myArray.join() );     // "hello,world,!"

// Any string can be used as separator...
console.log( myArray.join( " " ) );  // "hello world !";
console.log( myArray.join( "!!" ) ); // "hello!!world!!!";

// ...including an empty one.
console.log( myArray.join( "" ) );   // "helloworld!"

// 拼标签
"<tr><td>" + tdcell.join('</td><td>') + "</td></tr>"

方法-indexOf

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
//2

方法-slice

// Slicing
var myArray = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
var newArray = myArray.slice( 3 );

console.log( myArray );  // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
console.log( newArray ); // [ 4, 5, 6, 7, 8 ]

方法-splice

myArray.splice( index, length, values, ... );
Index – The starting index.
Length – The number of elements to remove.
Values – The values to be inserted at the index position.

var myArray = [ 0, 7, 8, 5 ];
myArray.splice( 1, 2, 1, 2, 3, 4 ); //from index 1, cut 2 elements, and insert 1,2,3,4
console.log( myArray ); // [ 0, 1, 2, 3, 4, 5 ]

方法-sort

// Sorting without comparing function.
var myArray = [ 3, 4, 6, 1 ];
myArray.sort(); // 1, 3, 4, 6

// Sorting with comparing function.
function descending( a, b ) {
    return b - a;
}
var myArray = [ 3, 4, 6, 1 ];
myArray.sort( descending ); // [ 6, 4, 3, 1 ]

方法-reverse

var myArray = [ "world" , "hello" ];
myArray.reverse(); // [ "hello", "world" ]

方法-shift

// Queue with shift() and push()
var myArray = [];

myArray.push( 0 ); // [ 0 ]
myArray.push( 2 ); // [ 0 , 2 ]
myArray.push( 7 ); // [ 0 , 2 , 7 ]
b = myArray.shift();   // [ 2 , 7 ],  b=0

方法-unshift

//Inserts an element at the first position of the array:
var myArray = [];

myArray.unshift( 0 ); // [ 0 ]
myArray.unshift( 2 ); // [ 2 , 0 ]
myArray.unshift( 7 ); // [ 7 , 2 , 0 ]

方法-forEach

Element – The element itself.
Index – The index of this element in the array.
Array – The array itself.

// Native .forEach()
function printElement( elem ) {
    console.log( elem );
}

function printElementAndIndex( elem, index ) {
    console.log( "Index " + index + ": " + elem );
}

function negateElement( elem, index, array ) {
    array[ index ] = -elem;
}

myArray = [ 1, 2, 3, 4, 5 ];

// Prints all elements to the console
myArray.forEach( printElement );

// Prints "Index 0: 1", "Index 1: 2", "Index 2: 3", ...
myArray.forEach( printElementAndIndex );

// myArray is now [ -1, -2, -3, -4, -5 ]
myArray.forEach( negateElement );

获取数字数组中最大最小值

var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);

清空一个数组

var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].

改变length可以进行数组截断或者扩增(扩增的项是undefined)

不要使用 delete 来删除一个数组中的项

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
delete items[3]; // return true
items.length; // return 11
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */

使用

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
items.splice(3,1) ;
items.length; // return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */

2.Object

Objects包含一个或多个键值对,键:任意字符串,值:数字,字符串,array,其他objects,函数等

声明

// Creating an object with the constructor:
var person1 = new Object;
person1.firstName = "John";
person1.lastName = "Doe";

alert( person1.firstName + " " + person1.lastName );

// Creating an object with the object literal syntax:
var person2 = {
    firstName: "Jane",
    lastName: "Doe"
};

alert( person2.firstName + " " + person2.lastName );

//包含方法
var myObject = {
    sayHello: function() {
        console.log( "hello" );
    },
    myName: "Rebecca"
};

myObject.sayHello(); // "hello"

console.log( myObject.myName ); // "Rebecca"

嵌套

// As mentioned, objects can also have objects as a property.
var people = {};

people[ "person1" ] = person1;
people[ "person2" ] = person2;

alert( people[ "person1" ].firstName );
alert( people[ "person2" ].firstName );

获取属性:寻址方式

name=person.lastname;
name=person["lastname"];

删除属性

b = { 'b1': 1, 'b2':2 }
delete b['b2']
//Object {b1: 1}

读取未定义的属性

// Properties that have not been created are undefined.
var person = { name: "John Doe" };
alert( person.email ); // undefined

访问对象的方法

objectName.methodName()

第四部分:内置对象

1.字符串(string)

字符串可以是引号中的任意文本

声明

// Single quotes can be used
var str = 'Our lovely string';

// Double quotes as well
var otherStr = "Another nice string";

//In Javascript, Strings can contain UTF-8 characters:
"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어";

连接字符串

//规则是:如果把数字与字符串相加,结果将成为字符串
var bigStr = 'Hi ' + 'JS strings are nice ' + 'and ' + 'easy to add';

长度

// Just use the property .length
var size = 'Our lovely string'.length;

常用方法

方法-trim

var str = "       Hello World!        ";
alert(str.trim());

方法-match

str.match("world")

方法-replace

语法

StringObject.replace(searchValue,replaceValue)

StringObject:字符串
searchValue:字符串或正则表达式
replaceValue:字符串或者函数

replaceValue可以是字符串。如果字符串中有几个特定字符的话,会被转换为特定字符串

$&  与正则相匹配的字符串
$`  匹配字符串左边的字符
$’ 匹配字符串右边的字符
$1,$2,$,3,…,$n 匹配结果中对应的分组匹配结果

实例

str.replace(/Microsoft/,"W3School")

a = 'hello world'
"hello world"
a.replace(/l/, 'a')
"healo world"
a.replace(/l/g, 'a')
"heaao worad"

var sStr='讨论一下正则表达式中的replace的用法';
sStr.replace(/正则表达式/,'{$&}');//讨论一下{正则表达式}中的replace的用法

'abc'.replace(/b/,"$`");//aac
'abc'.replace(/b/,"$'");//acc"'`")

'nimojs@126.com'.replace(/(.+)(@)(.*)/,"$2$1")//@nimojs

replaceValue 是函数

'JAVASCRIPT'.replace(/[A-G]/g,function(){
    return arguments[0].toLowerCase();
})//JaVaScRIPT

function logArguments(){    
    console.log(arguments);//["nimojs@126.com", "nimojs", "@", "126.com", 0, "nimojs@126.com"] 
    return '返回值会替换掉匹配到的目标'
}
console.log(
    'nimojs@126.com'.replace(/(.+)(@)(.*)/,logArguments)
)

方法-split(delimiter)

var s = "A,B,C,D";
var a = s.split(",");
document.write(a[2]);
//Returns C

方法-indexOf(substring,startPosition)

str.indexOf("Hello")
// if not exists, return -1
code.indexOf('a') === -1

webucator.indexOf("cat");
//Returns 4

webucator.indexOf("cat", 5);
//Returns -1

方法-lastIndexOf(substring,endPosition)

webucator.lastIndexOf("cat");
//Returns 4

 webucator.lastIndexOf("cat", 5);
 //Returns 4

方法-substr(startPosition,length)

webucator.substr(4, 3);
//Returns cat

webucator.substr(4);
//Returns cator

方法-substring(startPosition,endPosition)

webucator.substring(4, 7);
//Returns cat

webucator.substring(4);
//Returns cator

方法-slice(startPosition,endPosition)

webucator.slice(4, 7);
//Returns cat

var str="Hello happy world!"
str.slice(6)// happy world!
str.slice(6,11) //happy

方法-slice(startPosition,positionFromEnd)

webucator.slice(4, -2);
//Returns cat

方法-toLowerCase()/toUpperCase()

webucator.toLowerCase()
//Returns webucator

webucator.toUpperCase();
//Returns WEBUCATOR

方法-charAt(position)

webucator.charAt(4)
//Returns c (the fifth character)

方法-charCodeAt(position)

webucator.charCodeAt(4)
//Returns 99

方法-fromCharCode(characterCodes)

String.fromCharCode(169)
//Returns ©

2.math

Math(算数)对象的作用是:执行常见的算数任务

属性

//Math.PI Pi (Π)
Math.PI;
//3.141592653589793

//Math.SQRT2  Square root of 2.
Math.SQRT2;
//1.4142135623730951

Math.abs(number)

Math.abs(-12);
//Returns 12

Math.ceil(number)

Math.ceil(5.4);
//Returns 6

Math.floor(number)

Math.floor(5.6);
//Returns 5

Math.max(numbers)

Math.max(2, 5, 9, 3);
//Returns 9

Math.min(numbers)

Math.min(2, 5, 9, 3);
//Returns 2

Math.pow(number, power)

Math.pow(2, 5);
//Returns 32

Math.round(number)

Math.round(2.5);
//Returns 3

Math.random();

//Returns random
//number from 0 to 1
Math.random()
var rndDec = Math.random();

Math.power()

3.date

处理日期和时间

定义

//Syntax: new Date();
var myDate=new Date()
"从 1970/01/01 至今已过去 " + myDate.getTime() + " 毫秒"

var now = new Date();
document.write(now);

//Syntax: new Date("month dd, yyyy hh:mm:ss);")
var redSoxWin = new Date("October 21, 2004 12:01:00");
document.write(redSoxWin);

//Syntax: new Date(yyyy, mm, dd, hh, mm, ss, ms);
redSoxWin = new Date(2004, 9, 21, 12, 01, 00, 00);
document.write(redSoxWin);

// 计数从0开始
var d = new Date(2012, 4, 15);        // 2012年5月15日
alert(d.getMonth());            // 结果为4

Date.parse 的返回结果不是一个Date对象,而是从1970-01-01午夜(GMT)到给定日期之间的毫秒数。可以用Date的构造函数将其转换为Date对象

new Date(Date.parse("8/2/2012"));    // 正确识别为2012年8月2日
new Date(Date.parse("2012-08-02"));    // 正确识别为2012年8月2日
new Date(Date.parse("2012-8-2"));    // 不能识别

方法

getDate() Returns the day of the month (1-31).

rightNow.getDate();
//Returns 14

getDay() Returns the day of the week as a number (0-6, 0=Sunday, 6=Saturday).

rightNow.getDay();
//Returns 4

getMonth() Returns the month as a number (0-11, 0=January, 11=December).

rightNow.getMonth();
//Returns 3

getFullYear() Returns the four-digit year.

rightNow.getFullYear();
//Returns 2011

getHours() Returns the hour (0-23).

rightNow.getHours();
//Returns 0

getMinutes() Returns the minute (0-59).

rightNow.getMinutes();
//Returns 23

getSeconds() Returns the second (0-59).

rightNow.getSeconds();
//Returns 54

getMilliseconds() Returns the millisecond (0-999).

rightNow.getMilliseconds();
//Returns 650

getTime() Returns the number of milliseconds since midnight January 1, 1970.

rightNow.getTime();
//Returns 1113452634650

getTimezoneOffset() Returns the time difference in minutes between the computer of user and GMT.

rightNow.getTimezoneOffset();
//Returns 240

toLocaleString() Returns the Date object as a string.

rightNow.toLocaleString();
//Returns Thursday, April 14,
//2011 12:23:54 AM

toGMTString() Returns the Date object as a string in GMT timezone.

rightNow.toGMTString();
//Returns Thu, 14 Apr 2011
//04:23:54 UTC

4.boolean

布尔(逻辑)只能有两个值:true 或 false

var x=true
var y=false

对象

var myBoolean=new Boolean()

所有的代码行均会创建初始值为 false 的 Boolean 对象。

var myBoolean=new Boolean();
var myBoolean=new Boolean(0);
var myBoolean=new Boolean(null);
var myBoolean=new Boolean("");
var myBoolean=new Boolean(false);
var myBoolean=new Boolean(NaN);

所有的代码行均会创初始值为 true 的 Boolean 对象:

var myBoolean=new Boolean(1);
var myBoolean=new Boolean(true);
var myBoolean=new Boolean("true");
var myBoolean=new Boolean("false");
var myBoolean=new Boolean("Bill Gates");

第五部分: DOM操作

DOM

当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)。 HTML DOM 模型被构造为对象的树

HTML DOM 树

JavaScript 能够改变页面中的所有 HTML 元素
JavaScript 能够改变页面中的所有 HTML 属性
JavaScript 能够改变页面中的所有 CSS 样式
JavaScript 能够对页面中的所有事件做出反应

通过id查找

var x=document.getElementById("intro");

本例查找 id=“main” 的元素,然后查找 “main” 中的所有

元素:

var x=document.getElementById("main");
var y=x.getElementsByTagName("p");

改变输出

document.write(Date());

改变html

document.getElementById(id).innerHTML=new HTML

改变html属性

document.getElementById(id).attribute=new value

改变css

document.getElementById(id).style.property=new style

HTML Event Handlers

onblur ,onchange ,onclick ,ondblclick ,onfocus ,onkeydown ,onkeypress ,onkeyup ,onload ,onload ,onmousedown ,onmousemove ,onmouseout ,onmouseover ,onmouseup ,onreset ,onselect ,onsubmit ,onunload ,onunload

创建节点

<div id="div1">
<p id="p1">这是一个段落</p>
<p id="p2">这是另一个段落</p>
</div>

<script>
var para=document.createElement("p");
var node=document.createTextNode("这是新段落。");
para.appendChild(node);

var element=document.getElementById("div1");
element.appendChild(para);
</script>

删除节点

<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是另一个段落。</p>
</div>

<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>

第六部分:其他

1.正则

RegExp 对象用于存储检索模式。 通过 new 关键词来定义 RegExp 对象

var patt1=new RegExp("e");

RegExp 对象的方法 RegExp 对象有 3 个方法:test()、exec() 以及 compile()。

var patt1=new RegExp("e");
patt1.test("The best things in life are free"); //true

patt1.exec("The best things in life are free"); //["e"]

var patt1=new RegExp("e","g");
do
{
	result=patt1.exec("The best things in life are free");
	document.write(result);
}while (result!=null)

compile() 方法用于改变 RegExp。
compile() 既可以改变检索模式,也可以添加或删除第二个参数

var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
patt1.compile("d");
document.write(patt1.test("The best things in life are free"));

JavaScript中的正则有几个不同于其他语言的地方

2.this关键字

“this"是一个特殊的关键字,用在方法中,指向调用该方法的对象。this的值 In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used in methods to refer to the object on which a method is being invoked. The value of this is determined using a simple series of steps:

1.调用方式是Function.call() 或者 Function.apply(), this将会被赋值为传递给.call()/.apply()的第一个参数.如果第一个参数是null或者undefined,this会指向global object.

// A function invoked using Function.call()
var myObject = {
    sayHello: function() {
        console.log( "Hi! My name is " + this.myName );
    },
    myName: "Rebecca"
};

var secondObject = {
    myName: "Colin"
};

myObject.sayHello();                    // "Hi! My name is Rebecca"
myObject.sayHello.call( secondObject ); // "Hi! My name is Colin"

2.如果函数调用使用的是Function.bind(), this 会被赋值为传递给.bind()的第一个参数

// A function created using Function.bind()

var myName = "the global object";
var sayHello = function() {
    console.log( "Hi! My name is " + this.myName );
};
var myObject = {
    myName: "Rebecca"
};
var myObjectHello = sayHello.bind( myObject );

sayHello();      // "Hi! My name is the global object"
myObjectHello(); // "Hi! My name is Rebecca"

3.如果函数是作为对象的一个方法被调用,this指向该对象

// A function being attached to an object at runtime.

var myName = "the global object";
var sayHello = function() {
    console.log( "Hi! My name is " + this.myName );
};
var myObject = {
    myName: "Rebecca"
};
var secondObject = {
    myName: "Colin"
};

myObject.sayHello = sayHello;
secondObject.sayHello = sayHello;

sayHello();              // "Hi! My name is the global object"
myObject.sayHello();     // "Hi! My name is Rebecca"
secondObject.sayHello(); // "Hi! My name is Colin"

当在一个大的命名空间内调用函数,可以通过给一个变量赋值减少代码量,但是,注意方法赋值和对象赋值,在调用时this的区别,可能会会导致bug.

var myNamespace = {
    myObject: {
        sayHello: function() {
            console.log( "Hi! My name is " + this.myName );
        },
        myName: "Rebecca"
    }
};

var hello = myNamespace.myObject.sayHello;

hello(); // "Hi! My name is undefined"

or

var myNamespace = {
    myObject: {
        sayHello: function() {
            console.log( "Hi! My name is " + this.myName );
        },
        myName: "Rebecca"
    }
};

var obj = myNamespace.myObject;

obj.sayHello(); // "Hi! My name is Rebecca"

3.异常处理

语法

try
{
    //在这里运行代码
}catch(err)
{
    //在这里处理错误
}

e.g.

function message() {
    try {
        adddlert("Welcome guest!");
    }catch(err) {
        txt="There was an error on this page.\n\n";
        txt+="Error description: " + err.message + "\n\n";
        txt+="Click OK to continue.\n\n";
        alert(txt);
    }
}

throw 语句允许我们创建自定义错误。

正确的技术术语是:创建或抛出异常(exception)。
如果把 throw 与 try 和 catch 一起使用,那么您能够控制程序流,并生成自定义的错误消息。
语法
throw exception

function myFunction() {
    try {
        var x=document.getElementById("demo").value;
        if(x=="")    throw "empty";
        if(isNaN(x)) throw "not a number";
        if(x>10)     throw "too high";
        if(x<5)      throw "too low";
    } catch(err)
    {
        var y=document.getElementById("mess");
        y.innerHTML="Error: " + err + ".";
    }
}

4.作用域

Global Scope

如果一个变量或函数是全局的,可以在任意地方获取。对浏览器,全局作用域是window对象。

如果一个变量在函数外面定义,则这个变量是全局的

var x = 9;

//anywhere
window.x or x

Local Scope

在函数体中使用var定义的变量,是局部变量

function myFunc() {
    var x = 5;
}

console.log( x ); // ReferenceError: x is not defined

注意如果不适用var进行定义,则该变量默认全局

function myFunc() {
    x = 5;
}

console.log( x ); // 5

Immediately-Invoked Function Expressions(IIFE) 可以避免全局变量(立刻定义和调用),在jQuery库中可以看到

(function() {
    var jQuery = { /* All my methods go here. */ };
    window.jQuery = jQuery;
})();

局部变量在整个函数内可见,所以对于函数嵌套,内层可以访问外层变量:

function outer() {
    var x = 5;
    function inner() {
        console.log( x );
    }
    inner(); // 5
}

外层不能访问内层变量

function outer() {
    var x = 5;
    function inner() {
        console.log( x );
        var y = 10;
    }
    inner(); // 5
    console.log( y ); // ReferenceError: y is not defined
}

在函数中声明变量,没有使用var,javascript将作为全局变量处理,会到全局域去寻找该变量是否定义,如果未预定义,将会在全局域中定义该变量,造成一些不可预期的结果。

// Functions have access to variables defined in the same scope.

var foo = "hello";

var sayHello = function() {
    console.log( foo );
};

sayHello(); // "hello"

console.log( foo ); // "hello"

全局变量和局部变量可以重名

var foo = "world";
var sayHello = function() {
    var foo = "hello";
    console.log( foo );
};

sayHello(); // "hello"

console.log( foo ); // "world"

When, within a function, you reference a variable defined in an outer scope, that function can see changes to the variable’s value after the function is defined.

var myFunction = function() {
    var foo = "hello";
    var myFn = function() {
        console.log( foo ); //指向该变量
    };
    foo = "world"; // change 变量对应的值变更了
    return myFn;
};

var f = myFunction();

f(); // "world"

一个复杂的例子演示:

(function() {
    var baz = 1;
    var bim = function() {
        console.log( baz );
    };
    bar = function() {
        console.log( baz );
    };
})();

console.log( baz ); // baz is not defined outside of the function, ReferenceError

bar(); //  1, 外部可见,全局的

bim(); // ReferenceError: bim is not defined

局部变量会在函数运行以后被删除。

全局变量会在页面关闭后被删除。

5.闭包

可以参考 入口

简单例子

var buildMultiplier = function(x) {
    return function(y) {
        return x * y;
    }
}

var double = buildMultiplier(2);
var triple = buildMultiplier(3);

double(3); // => 6
triple(3); // => 9

Closures are an extension of the concept of scope.

通过闭包,函数可以获取在函数定义位置作用域范围内的变量

闭包需要通过实例去理解。

下面这个例子,最终每个函数的i将会是函数循环结果的最后一个值

// Each function executed within the loop will reference
// the last value stored in i (5).
// This won't behave as we want it to - every 100 milliseconds, 5 will alert
for ( var i = 0; i < 5; i++ ) {
    setTimeout(function() {
        alert( i );
    }, i * 100 );
}

闭包可以避免这种情况,为每个循环建立独立的可见范围–将变量的每个独立值存储在其可见域内。

// Using a closure to create a new private scope
// fix: “close” the value of i inside createFunction, so it won't change
var createFunction = function( i ) { //可见范围,i被保存,独立
    return function() {
        alert( i );
    };
};

for ( var i = 0; i < 5; i++ ) {
    setTimeout( createFunction( i ), i * 100 );
}

闭包还通常和this关键字配合

// Using a closure to access inner and outer object instances simultaneously.
var outerObj = {
    myName: "outer",
    outerFunction: function() {

        // Provide a reference to outerObj through innerFunction's closure
        var self = this;
        var innerObj = {
            myName: "inner",
            innerFunction: function() {
                console.log( self.myName, this.myName ); // "outer inner"
            }
        };

        innerObj.innerFunction();

        console.log( this.myName ); // "outer"
    }
};

6.typeof(Testing Type)

typeof关键之用于判断一个变量的类型

type checking

// Testing the type of various variables.
var myFunction = function() {
    console.log( "hello" );
};
var myObject = {
    foo: "bar"
};
var myArray = [ "a", "b", "c" ];
var myString = "hello";
var myNumber = 3;
var myRegExp = /(\w+)\s(\w+)/;

typeof myFunction; // "function"
typeof myObject;   // "object"
typeof myArray;    // "object" -- Careful!
typeof myString;   // "string"
typeof myNumber;   // "number"
typeof null;       // "object" -- Careful!
typeof undefined;  // "undefined"
typeof meh;        // "undefined" -- undefined variable.
typeof myRegExp;   // "function" or "object" depending on environment.


if ( myArray.push && myArray.slice && myArray.join ) {
    // probably an array (this is called "duck typing")
}

if ( Object.prototype.toString.call( myArray ) === "[object Array]" ) {
    // Definitely an array!
    // This is widely considered as the most robust way
    // to determine if a specific value is an Array.
}

7.Timers

Timers are started and stopped with the following four methods of the window object:

setTimeout(code_to_execute, wait_time_in_milliseconds)
clearTimeout(timer)

setInterval(code_to_execute, interval_in_milliseconds)
clearInterval(interval)

test

<script type="text/javascript">
    var timer;
    function changeBg(color) {
        timer = setTimeout(function() { document.bgColor=color; }, 1000);
    }

    function stopTimer() {
        clearTimeout(timer);
    }
</script>
</head>
<body>
<button onclick="changeBg('red')">Change Background to Red</button>
<button onclick="changeBg('white')">Change Background to White</button>
<button onclick="stopTimer()">Wait! Don't do it!</button>