遍歷數組/對象的幾種方式
常用的方法:
for、for in、for of(es6語法)、forEach、map、filter、$.each、$.map
注:本篇文章demo只涉及遍歷數組元素
- 只能遍歷數組:
for、forEach、map、filter(map和filter會返回一個新數組)
- 可以遍歷數組和非數組對象:
for in、for of(es6語法-只能遍歷部署了 Iterator 接口的對象)、$.each、$.map
注:默認遍歷后都不會改變原數組,除非手動在遍歷內容體中去改變原數組。
// 聲明幾個需要用到的變量
var arr = [1, 78, 90, "hello", 22], results = [];
1、 使用for循環遍歷
for (var i, len = arr.length; i < len; i++) {
console.log("for=>index=" + i + "/value=" + arr[i]);
}
注:用for循環遍歷,使用臨時變量,將長度緩存起來,避免重復獲取數組長度,提高效率
2、使用for in循環遍歷
for (var i in arr) {
console.log("for in=>index=" + i + "/value=" + arr[i]);
}
注:據說這個效率是循環遍歷中效率最低的
3、使用for of循環遍歷[es6語法]
for (let value of arr) {
console.log("for of=>value=" + value);
}
注:性能優于for in,value代表的是屬性值
4、使用forEach遍歷
results = arr.forEach(function (value, index, array) {
console.log("forEach=>" + index + ": " + value + "/" + array[index]);
return value;
});
console.log("forEach=>results=" + results); // =>undefined
其中value參數是必須的,代表當前元素的值。forEach返回值為undefined
5、使用map遍歷
results = arr.map(function (value, index, array) {
console.log("map=>" + index + ": " + value + "/" + array[index]);
return value + index;
});
console.log("map=>results=" + results); // =>1,79,92,hello3,26
(1):其中value參數是必須的,代表當前元素的值
(2):map返回一個新數組,數組中的元素為原始數組元素調用函數處理后的值,不會改變原數組,返回值是什么就是什么,如果不做其它處理的新數組長度和原始數組長度相等*
6、使用filter遍歷
results = arr.filter(function (value, index, array) {
console.log("filter=>" + index + ": " + value + "/" + array[index]);
return isNaN(value) ? "" : value;
});
console.log("filter=>results=" + results); // =>1,78,90,22
(1):其中value參數是必須的,代表當前元素的值
(2):使用filter方法創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素,不會改變原數組,返回值如果是false類型的即刪除該元素
(3):jquery的方法filter只是對jQuery對象進行一個過濾,篩選出與指定表達式匹配的元素集合。如:$("p").filter(".selected"); // 保留帶有select類的p元素
*
7、使用jQuery核心方法$.each遍歷數組
$.each(arr, function (index, value) {
console.log("$.each=>index=" + index + "/value=" + value);
});
注:該方法也可以用來操作jQuery對象,如:$("div").each(callback)
// 對匹配到的div元素執行相關操作
8、使用jQuery核心方法$.map遍歷數組
results = $.map(arr, function (value, index) {
console.log("$.each=>index=" + index + "/value=" + value);
return isNaN(value) ? null : value;
// 返回null(刪除數組中的項目),不能返回"",只是將對應的數組元素置為長度為0的字符串
});
console.log(arr + "=======" + results); // 1,78,90,hello,22=======1,78,90,22
該方法也可以用來操作jQuery對象,如:
$("p").append( $("input").map(function(){
return $(this).val();
}).get().join(", ") );