數(shù)組的常見的幾種方法

數(shù)組的常見的幾種方法

1. 數(shù)組屬于一種特殊的對象

typeof [1, 2, 3] // "object"


2. 數(shù)組的key是 0,1,2...

var arr = ['a','b','c']

Object.key(arr)? //返回 ['0','1','2']

Object.key是返回數(shù)組的key值得方法


3.獲取數(shù)組值的方法

arr[key]

//因單獨的數(shù)字不能作為標識符,所以arr.0/1/2...不合法


4. 可通過數(shù)組的length屬性來減少數(shù)組成員或清空數(shù)組

var? arr = [1,2,3]

arr.length // 3

arr.length === 2

arr // [1,2]

arr.length === 0 // 使length為0清空數(shù)組

arr //[]


5.檢查某個 key 是否存在的 in 運算符

in 運算符不僅使用與對象? 同樣適用于數(shù)組

var arr = ['a','b','c']

2 in arr? ?//true

100 in arr //false

'a' in arr? //false


6.遍歷數(shù)組的幾種方法

?for...in... 方法循環(huán)不僅可以遍歷對象,也可以遍歷數(shù)組,因為數(shù)組是一種特殊對象。

var arr = ['a','b','c']

for (var i in arr){

console.log(i+‘:’+arr[i])

}

//0:a

//1:b

//2:c


for...in 方法遍歷數(shù)組時也會遍歷到非數(shù)組鍵

var arr = ['a','b','c']

arr.abc=100

for (var i in arr){

console.log(i+‘:’+arr[i])

}//0:a

//1:b

//2:c

//abc:100


所以在遍歷數(shù)組時,使用for循環(huán)可以避免遍歷到非數(shù)字鍵

var a = [1, 2, 3];

// for循環(huán)

for(var i = 0; i < a.length; i++) {

console.log(a[i]);

}


for(var i = a.length;i>=0;i--){

console.log(a[i]);

}

// while循環(huán)

var i = 0;

while (i < a.length) {

console.log(a[i]); i++;

}

var l = a.length;

while (l--) {

console.log(a[l]);

}

以上是for while的正逆向便利方法



遍歷數(shù)組的forEach方法

var arr = ['a','b','c']

arr.forEach(function(even){

console.log(even)

})

//a

//b

//c

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容