定義一個(gè)對(duì)象數(shù)組
find()方法為數(shù)組中的每個(gè)元素都調(diào)用一次函數(shù)執(zhí)行渺鹦,
當(dāng)數(shù)組中的元素在測(cè)試條件時(shí)返回true,find()返回符合條件的元素,之后的值不會(huì)再執(zhí)行函數(shù)舞丛。
如果沒有符合條件的元素則返回undefined。
var ar = arr.find(function(elem){
return elem.age>2;
});
console.log(ar);//{id:3, name:'王五', age:3}
console.log(arr);
filter():創(chuàng)建一個(gè)新數(shù)組果漾,新數(shù)組中的元素是通過檢查指定數(shù)組中符合條件的所有元素
var arr = [1,2,3,4,5,6,7];
var ar = arr.filter(function(elem){
return elem>5;
});
console.log(ar);//[6,7]
console.log(arr);//[1,2,3,4,5,6,7]
array.map(function(value, index, arr),thisValue)
value:必須球切,代表當(dāng)前元素,其他四個(gè)參數(shù)都是可選绒障,index代表當(dāng)前索引值吨凑,arr代表當(dāng)前的數(shù)組,thisValue代表傳遞給函數(shù)的值户辱,一般用this值怀骤,如果這個(gè)參數(shù)為空,undefined會(huì)傳遞給this值
返回值:返回一個(gè)新數(shù)組焕妙,數(shù)組中的元素為原始數(shù)組元素調(diào)用函數(shù)處理后的值
var arr = [1,2,3,4,5,6,7];
var ar = arr.map(function(elem){
return elem*4;
});
console.log(ar);//[4, 8, 12, 16, 20, 24, 28]
console.log(arr);//[1,2,3,4,5,6,7]
array.forEach(function(value, index, arr),thisValue)
forEach():用于調(diào)用數(shù)組每個(gè)元素弓摘,并將元素傳遞給回調(diào)函數(shù)(注意沒有辦法跳出或終止forEach語句焚鹊,除非拋出異常)
value:必須,代表當(dāng)前元素韧献,其他四個(gè)參數(shù)都是可選末患,index代表當(dāng)前索引值,arr代表當(dāng)前的數(shù)組锤窑,thisValue代表傳遞給函數(shù)的值璧针,一般用this值,如果這個(gè)參數(shù)為空渊啰,undefined會(huì)傳遞給this值
返回值:undefined
var arr = [1,2,3,4,5,6,7];
var sum = 0;
var ar = arr.forEach(function(elem){
sum+=elem*4;
});
console.log(ar);//undefined
console.log(arr);//[1,2,3,4,5,6,7]
console.log(sum);//112
for in 不建議使用
for(let index in arr) {
console.log(index)
console.log(arr[index])
? ? ? ? arr[index].age=arr[index].age+10
? };
? ? console.log(arr);
for(let ar of arr) {
console.log(ar)
? ? ? ? ar.age=ar.age+10
? };
? ? console.log(arr)
find()方法主要用來返回?cái)?shù)組中符合條件的第一個(gè)元素(沒有的話探橱,返回undefined)
filter()方法主要用來篩選數(shù)組中符合條件的所有元素申屹,并且放在一個(gè)新數(shù)組中,如果沒有隧膏,返回一個(gè)空數(shù)組
map()方法主要用來對(duì)數(shù)組中的元素調(diào)用函數(shù)進(jìn)行處理哗讥,并且把處理結(jié)果放在一個(gè)新數(shù)組中返回(如果沒有返回值,新數(shù)組中的每一個(gè)元素都為undefined)
forEach()方法也是用于對(duì)數(shù)組中的每一個(gè)元素執(zhí)行一次回調(diào)函數(shù)胞枕,但它沒有返回值(或者說它的返回值為undefined杆煞,即便我們?cè)诨卣{(diào)函數(shù)中寫了return語句,返回值依然為undefined)
for in 和for of 不建議用