數組
周遊
普通周遊
for
最簡單的一種,也是使用頻率最高的一種。
let arr = ['a', 'b', 'c', 'd', 'e']
for (let i = 0; i < arr.length; i++) {
console.log(i, ' => ', arr[i])
}
優化: 緩存數組長度:
let arr = ['a', 'b', 'c', 'd', 'e']
for (let i = 0, len = arr.length; i < len; i++) {
console.log(i, ' => ', arr[i])
}
使用臨時變量,将長度緩存起來,避免重複擷取數組長度,當數組較大時優化效果才會比較明顯。
for-in
這個循環很多人愛用,但實際上,經分析測試,在衆多的循環周遊方式中它的效率是最低的。
let arr = ['a', 'b', 'c', 'd', 'e']
for (let i in arr) {
console.log(i, ' => ', arr[i])
}
for-of
這種方式是es6裡面用到的,性能要好于forin,但仍然比不上普通for循環。
let arr = ['a', 'b', 'c', 'd', 'e']
let index = 0
for (let item of arr) {
console.log(index++, ' => ', item)
}
forEach
數組自帶的foreach循環,使用頻率較高,實際上性能比普通for循環弱。
let arr = ['a', 'b', 'c', 'd', 'e']
arr.forEach((v, k) => {
console.log(k, ' => ', v)
})
forEach接受第三個參數,指向原數組,沒有傳回值,對其進行操作會改變原數組對象
let ary = [12, 23, 24, 42, 1]
let res = ary.forEach((item, index, input) => {
input[index] = item * 10
})
console.log(res) //-->undefined
console.log(ary) //-->會對原來的數組産生改變
如果版本低的浏覽器不相容(IE8-),可以自定義方法實作:
/**
* forEach周遊數組
* @param callback [function] 回調函數;
* @param context [object] 上下文;
*/
Array.prototype.myForEach = function (callback,context) {
context = context || window;
if('forEach' in Array.prototype) {
this.forEach(callback,context)
return
}
// IE6-8下自己編寫回調函數執行的邏輯
for(let i = 0,len = this.length; i < len; i++) {
callback && callback.call(context, this[i], i, this)
}
}
let arr = [12, 23, 24, 42, 1]
arr.myForEach((v, k) => {
console.log(k, ' => ', v)
})
map
map會傳回一個全新的數組,同樣接受第三個參數,如果對其進行操作會改變原數組。
let ary = [12, 23, 24, 42, 1]
let res = ary.map((item, index, input) => {
return item * 10
})
console.log(res) //-->[120,230,240,420,10]
console.log(ary) //-->[12,23,24,42,1]
如果版本低的浏覽器不相容(IE8-),可以自定義方法實作:
/**
* map周遊數組
* @param callback [function] 回調函數;
* @param context [object] 上下文;
*/
Array.prototype.myMap = function myMap(callback,context){
context = context || window
if('map' in Array.prototype) {
return this.map(callback, context)
}
//IE6-8下自己編寫回調函數執行的邏輯
let newAry = []
for(var i = 0,len = this.length; i < len; i++) {
if(typeof callback === 'function') {
var val = callback.call(context, this[i], i, this)
newAry[newAry.length] = val
}
}
return newAry
}
arr.myMap((v, k) => {
console.log(k, ' => ', v)
})
過濾
filter
對數組中的每個元素都執行一次指定的函數(callback),并且建立一個新的數組,該數組元素是所有回調函數執行時傳回值為 true 的原數組元素。它隻對數組中的非空元素執行指定的函數,沒有指派或者已經删除的元素将被忽略,同時,新建立的數組也不會包含這些元素。
let arr = [12, 5, 8, 130, 44]
let ret = arr.filter((el, index, array) => {
return el > 10
})
console.log(ret) // [12, 130, 44]
map
map也可以作為過濾器使用,不過傳回的是對原數組每項元素進行操作變換後的數組,而不是每項元素傳回為true的元素集合。
let strings = ["hello", "Array", "WORLD"]
function makeUpperCase(v) {
return v.toUpperCase()
}
let uppers = strings.map(makeUpperCase)
console.log(uppers) // ["HELLO", "ARRAY", "WORLD"]
some
對數組中的每個元素都執行一次指定的函數(callback),直到此函數傳回 true,如果發現這個元素,some 将傳回 true,如果回調函數對每個元素執行後都傳回 false ,some 将傳回 false。它隻對數組中的非空元素執行指定的函數,沒有指派或者已經删除的元素将被忽略。
// 檢查是否有數組元素大于等于10:
function isBigEnough(element, index, array) {
return (element >= 10)
}
let passed1 = [2, 5, 8, 1, 4].some(isBigEnough) // passed1 is false
let passed2 = [12, 5, 8, 1, 4].some(isBigEnough) // passed2 is true
every
對數組中的每個元素都執行一次指定的函數(callback),直到此函數傳回 false,如果發現這個元素,every 将傳回 false,如果回調函數對每個元素執行後都傳回 true ,every 将傳回 true。它隻對數組中的非空元素執行指定的函數,沒有指派或者已經删除的元素将被忽略。
// 測試是否所有數組元素都大于等于10:
function isBigEnough(element, index, array) {
return (element >= 10)
}
let passed1 = [12, 5, 8, 1, 4].every(isBigEnough) // passed1 is false
let passed2 = [12, 15, 18, 11, 14].every(isBigEnough) // passed2 is true
排序
let arr = ['a', 1, 'b', 3, 'c', 2, 'd', 'e']
console.log(arr) // ["a", 1, "b", 3, "c", 2, "d", "e"]
console.log(arr.reverse()) // 反轉元素(改變原數組) // ["e", "d", 2, "c", 3, "b", 1, "a"]
console.log(arr.sort()) // 對數組元素排序(改變原數組) // [1, 2, 3, "a", "b", "c", "d", "e"]
console.log(arr) // [1, 2, 3, "a", "b", "c", "d", "e"]
sort自定義排序
let arr = [1, 100, 52, 6, 88, 99]
let arr1 = arr.sort((a, b) => a-b) // 從小到大排序
console.log(arr1) // [1, 6, 52, 88, 99, 100]
let arr2 = arr.sort((a, b) => b-a) // 從大到小排序
console.log(arr2) // [100, 99, 88, 52, 6, 1]
console.log(arr) // 原數組也發生改變
搜尋
let arr = [12, 5, 4, 8, 1, 4]
arr.indexOf(4) // 2,從前往後搜尋,傳回第一次搜尋到的數組下标,搜尋不到傳回-1
arr.lastIndexOf(4) // 5,從後往前搜尋,傳回第一次搜尋到的數組下标,搜尋不到傳回-1
arr.indexOf(0) // -1
增删、清空操作
添加元素
let arr = ['a', 'b', 'c', 'd', 'e']
arr.push(10, 11) // 模仿棧進行操作,往數組末尾添加一個或多個元素(改變原數組)
arr.unshift(0, 1) // 模仿隊列進行操作,往數組前端添加一個或多個元素(改變原數組)
console.log(arr) // [0, 1, "a", "b", 'c', "d", "e", 10, 11]
删除元素
arr.pop() // 移除最後一個元素并傳回該元素值(改變原數組)
arr.shift() // 移除最前一個元素并傳回該元素值,數組中元素自動前移(改變原數組)
console.log(arr) // ["b", "c", "d"]
清空數組
将數組的length設定為0即可
let arr = ['a', 1, 'b', 3, 'c', 2, 'd', 'e']
arr.length = 0
length詳解:
因為數組的索引總是由0開始,是以一個數組的上下限分别是:0和length-1;當length屬性被設定得更大時,整個數組的狀态事實上不會發生變化,僅僅是length屬性變大;當length屬性被設定得比原來小時,則原先數組中索引大于或等于length的元素的值全部被丢失。
splice
既可以删除也可以添加元素
let arr = ['a', 'b', 'c', 'd', 'e']
arr.splice(2, 1, 1,2,3)
console.log(arr) // ["a", "b", 1, 2, 3, "d", "e"]
splice(start, len, elems) : 删除并添加元素(改變原數組)
start: 起始位置
len: 删除元素的長度
elems: 添加的元素隊列
幾種形式:
splice(start, 0, elems) : 從start位置添加元素
splice(start, len) : 從start位置删除len個元素
截取、合并與拷貝
let arr = ['a', 'b', 'c', 'd', 'e']
let arr1 = arr.slice(1, 2) // 以數組的形式傳回數組的一部分,注意不包括 end 對應的元素,如果省略 end 将複制 start 之後的所有元素(傳回新數組)
let arr2 = arr.concat([1,2,3]); // 将多個數組(也可以是字元串,或者是數組和字元串的混合)連接配接為一個數組(傳回新數組)
console.log(arr) // ["a", "b", "c", "d", "e"]
console.log(arr1) // ["b"]
console.log(arr2) // ["a", "b", "c", "d", "e", 1, 2, 3]
其實slice和concat也可以作為數組的拷貝方法:
arr.slice(0) // 傳回數組的拷貝數組,注意是一個新的數組,不是指向
arr.concat() // 傳回數組的拷貝數組,注意是一個新的數組,不是指向
Map
Map是一組鍵值對的結構,具有極快的查找速度。
建立
方法一: 建立的時候初始化
let mapObj = new Map([
['a', 1],
['b', 2],
['c', 3]
])
console.log(mapObj.size) // 3
方法二: 建立空Map,之後添加元素
let mapObj = new Map()
mapObj.set('a', 1)
mapObj.set('b', 2)
mapObj.set('c', 3)
console.log(mapObj.size) // 3
注意: Map對象的長度不是length,而是size
基礎操作
Map對象的建立、添加元素、删除元素…
mapObj.set('a', 1) // 添加元素
mapObj.delete('d') // 删除指定元素
mapObj.has('a') // true
mapObj.get('a') // 1
周遊
使用上面建立的Map進行操作
forEach
同數組的forEach周遊,三個參數分别代表: value、key、map本身
mapObj.forEach((e, index, self) => {
console.log(index, ' => ', e)
})
列印出:
a => 1
b => 2
c => 3
for-of
for (const e of mapObj) {
console.log(e)
}
列印出:
["a", 1]
["b", 2]
["c", 3]
注意: for-of周遊出來的是一個數組,其中e[0]為key,e[1]為value
Set
Set和Map類似,但set隻存儲key,且key不重複。
建立
方法一: 建立的時候初始化
let setObj = new Set([1, 2, 3])
console.log(setObj.size)
方法二: 建立空Map,之後添加元素
let setObj = new Set()
setObj.add(1)
setObj.add(2)
setObj.add(3)
console.log(setObj.size)
注意: Map對象的長度不是length,而是size
基礎操作
let s = new Set([1, 2, 3])
s.add(3) // 由于key重複,添加不進
s.delete(3) // 删除指定key
console.log(s) // 1 2
周遊
使用上面建立的Set進行操作
forEach
Set與Array類似,但Set沒有索引,是以回調函數的前兩個參數都是元素本身
s1.forEach(function (element, sameElement, set) {
console.log(element) // element === sameElement
})
// 列印 1 2 3
for-of
for (const item of s1) {
console.log(item)
}
// 列印 1 2 3
類數組對象
JavaScript中,數組是一個特殊的對象,其property名為正整數,且其length屬性會随着數組成員的增減而發生變化,同時又從Array構造函數中繼承了一些用于進行數組操作的方法。而對于一個普通的對象來說:
如果它的所有property名均為正整數,同時也有相應的length屬性,那麼雖然該對象并不是由Array構造函數所建立的,它依然呈現出數組的行為,在這種情況下,這些對象被稱為“類數組對象”。
形如:
let obj = {
0: 'qzy',
1: 22,
2: false,
length: 3
}
類數組對象可以使用Array對象原生方法進行操作。
周遊
沿用上述對象進行操作
forEach
Array.prototype.forEach.call(obj, function(el, index){
console.log(index, ' => ', el)
})
map
Array.prototype.map.call(obj, function(el, index){
console.log(index, ' => ', el)
})
注意: 類數組對象不支援使用for-of進行周遊,否則會報錯: [Symbol.iterator] is not a function
增删截取操作
沿用上述對象進行操作
Array.prototype.join.call(obj, '-') // qzy-22-false
Array.prototype.slice.call(obj, 1, 2) // [22]
Array.prototype.push.call(obj, 5) // Object {0: "qzy", 1: 22, 2: false, 3: 5, length: 4}
String也是一個類數組對象
由于字元串對象也存在length,且序号從0開始增加,是以字元串也可以看做一個隻讀的類數組對象,這意味着String對象可以使用Array的所有原型方法。
let str = 'hello world'
console.log(Array.prototype.slice.call(str, 0, 5)) // ["h", "e", "l", "l", "o"]
String也可以使用for-of進行周遊
let str = 'hello world'
for (const s of str) {
console.log(s)
}
String獨有方法
除了使用Array原型對象的方法,String還包含其他一些自己獨有的方法:
與Array使用方法相同的方法
搜尋: indexOf()、lastIndexOf()、concat()
轉換: toLowerCase()、toUpperCase()
截取
substr(start, len)
substring(start, end)
slice(start, end)
let str = 'hello world'
let ret1 = str.substr(6, 5) // "world"
let ret2 = str.substring(6, 11) // "world"
let ret3 = str.slice(3, 8) // "lo wo"
substring 是以兩個參數中較小一個作為起始位置,較大的參數作為結束位置。
slice 是第一參數為起始位置,第二參數為結束位置,如果結束位置小于起始位置傳回空字元串
console.log(str.substring(11, 6) === str.substring(6, 11)) // true
接收負數為參數時:
slice會将它字元串的長度與對應的負數相加,結果作為參數;
substr則僅僅是将第一個參數與字元串長度相加後的結果作為第一個參數;
substring則幹脆将負參數都直接轉換為0。
let str = 'hello world'
let ret1 = str.substr(-5) // "world"
let ret2 = str.substr(-5, 3) // "wor"
let ret3 = str.substring(6, -1) // "hello"
let ret4 = str.slice(6, -1) // "worl"
console.log(ret1 === str.substr(str.length - 5)) // true
console.log(ret2 === str.substr(str.length - 5, 3)) // true
console.log(ret3 === str.substring(6, 0)) // true
console.log(ret4 === str.slice(6, str.length - 1)) // true
正則
match()
replace()
search()
let str = 'hello world'
let ret0 = str.match(/r/) // 非全局搜尋,傳回比對的第一個字元串數組(length為1),包括index和input
let ret1 = str.match(/o/g) // 全局搜尋,傳回比對的字元串數組,length為搜尋到的比對正規表達式的長度
let ret2 = str.replace(/o/g, 'e') // 全局替換
let ret3 = str.replace(/O/i, 'e') // 不區分大小寫,隻替換搜尋到的第一個字串
let ret4 = str.search(/l/) // 傳回搜尋到的第一個比對字串的索引
let ret5 = str.search(/l/g) // 全局無效,同上
console.log(ret0) // ["r", index: 8, input: "hello world"]
console.log(ret1) // ["o", "o"]
console.log(ret2) // "helle werld"
console.log(ret3) // "helle world"
console.log(ret4) // 2
console.log(ret5) // 2
console.log(str) // 不改變源字元串 'hello world'
轉化
Map => Object
let mapObj = new Map([ ['a', 1], ['b', 2], ['c', 3] ])
let obj = {}
for (const item of mapObj) {
obj[item[0]] = item[1]
}
console.log(obj)
Set => Array
let setObj = new Set([1, 2, 3])
let arr = []
for (const item of setObj) {
arr.push(item)
}
console.log(arr)
Array => String
arr.join(separator)
['a', 'b', 'c', 'd', 'e'].join('')
// toLocaleString 、toString 、valueOf:可以看作是join的特殊用法,不常用
String => Array
str.split(separator)
'hello world'.split(' ') // ["hello", "world"]