ES5:
1.嚴格模式:
調用方法: "use strict" ;
作用范圍:全局模式:放在腳本文件的第一行,則整個腳本文件都將以“嚴格模式”運行。
局部模式:將"use strict"放到函數內的第一行。
嚴格模式的語法要求:
① 必須用var聲明變量
"use strict";
a = 10;
console.log(a); //報錯
②函數內不允許出現重名參數
"use strict";
function fn(a,b,b){
console.log(a);
console.log(b);
}
fn(2,3,4) //報錯
③this無法指向全局變量window
"use strict";
function fn(){
console.log(this);
}
fn(); //undefined
④arguments對象不允許被動態改變
"use strict";
function fn(a,b){
a = 20;
console.log(a);
console.log(b);
console.log(arguments); //2,3
}
fn(2,3)
2.ES5新增數組常見方法:
①indexOf:
語法: arr.indexOf(item,start);
返回數組中某個元素的位置,沒有找到指定元素返回-1.
lastIndexOf():從后面往前找,返回某個元素的首次出現的位置。
var arr=[1,2,3,4,5,2]
console.log(arr.indexOf(2)); //1
console.log(arr.lastIndexOf(2)); //5
console.log(arr.indexOf(6)); //-1
②forEach:
語法: array.forEach(function(value,index,arr));
用於調用數組的每個元素,並將元素傳遞給回調函數,沒有任何返回值。
回調函數內的三個參數分別為:當前循環的值(必選),當前循環的索引(可選),當前數組本身(可選)。
var arr = ["a","b",255,512,"hello"];
var a = arr.forEach(function(value,index){
console.log(value); //a b 255 512 hello
console.log(index); //0 1 2 3 4
})
console.log(a); //undefined
③map:
語法: array.map(function(value,index,arr));
返回一個被操作后的新數組,不會改變原數組,一般配合return使用.
var arr=[1,2,3,4,5]
var arr2=arr.map(function(value){
return value+5;
})
console.log(arr); //1,2,3,4,5
console.log(arr2); //6,7,8,9,10
④filter:
語法: array.filter(function(value,index,arr));
過濾不符合條件的元素,如果回調函數返回true則保留,返回false則過濾掉。不會改變原數組
arr3=arr2.filter(function(value){
return value>7
})
console.log(arr2); //6,7,8,9,10
console.log(arr3); //8,9,10
3.字符串常見API
API(Application Programming Interface,應用程序編程接口)是一些預先定義的函數
①indexOf(date,start)
用於返回字符串中規定字符的位置,返回字符所在位置的下標,若無返回-1.
var str="helloworld";
console.log(str.indexOf("o")); //4
②charAt(index); 返回指定位置(下標)的字符
var str="helloworld";
console.log(str.charAt("2")); //l
③substring(n,m) 返回從指定位置,到結束位置(不含)的字符串。
console.log(str.substring(1,8)) //ellowo
④slice(n,m); 同substring
substring(n,m)和slice(n,m)的區別:
console.log(str.slice(-3)); //rld
console.log(str.substring(-3)); //helloworld
console.log(str.slice(3,-4)); //low
console.log(str.substring(3,-4)); //hel
slice將傳入負值與字符串長度(string.length)相加,可以操作數組;substring會將所有負值都轉換成0,不可以操作數組。
⑤split("");通過指定字符分割字符串,返回一個數組。
var str="1,2,3,4,5,6,7";
var arr=str.split(",");
console.log(arr); //["1", "2", "3", "4", "5", "6", "7"]
⑥replace("需要替換的字符串","替換之后的字符串") ,默認只替換一次
var str="1,2,3,4,2,6,7,2";
var str2=str.replace(2,5);
console.log(str2); //1,5,3,4,2,6,7,2
var str3=str.replace("/2/g",5); //g為正則修飾符,表示全局匹配
console.log(str3); //1,5,3,4,5,6,7,5