1 var arr = ["first","second","third","fourth",3,5,8]; 2 for(var i = 0; i < arr.length;i++){ 3 console.log(arr[i]); 4 } 5 //输出: 6 first 7 second 8 third 9 fourth 10 3 11 5 12 8
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 for(var i in arr){ 3 console.log(arr[i] +'/' + i); 4 } 5 //输出结果为: 6 first/0 7 second/1 8 third/2 9 fourth/3 10 3/4 11 5/5 12 8/6
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 for(var item of arr){ 3 console.log(item); 4 } 5 //输出结果: 6 first 7 second 8 third 9 fourth 10 3 11 5 12 8
虽然for… in 、 for… of 都可以变历数组,可是二者仍是有很大区别的,先说结论:数组
二者的主要区别在于他们的迭代方式 函数
2.foreach方法:被传递给foreach的函数会在数组的每一个元素上执行一次,元素做为参数传递给该函数测试
1 var arr = ["first","second","third","fourth",3,5,8]; 2 //element 表示arr的单元项,index 表示arr单元项对应的索引值 3 arr.forEach(function(element,index){ 4 console.log(element + '/' + index); 5 6 }) 7 //输出结果: 8 first/0 9 second/1 10 third/2 11 fourth/3 12 3/4 13 5/5 14 8/6
1 var arr1 = ["first","second", ,"fourth",3,5,8]; 2 arr1.forEach(function(element,index){ 3 console.log(element + '/' + index); 4 5 }) 6 //输出结果 7 first/0 8 second/1 9 fourth/3 10 3/4 11 5/5 12 8/6
1 var arr = ["first","second",'third' ,"fourth"]; 2 var arr2 = arr.map(function(item){ 3 return item.toUpperCase(); 4 }) 5 console.log(arr2); 6 //输出: 7 [FIRST,SECOND,THIRD, FOURTH]
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 var arr3 = arr.filter(function(item){ 3 if(typeof item == 'number'){ 4 return item; 5 } 6 }) 7 console.log(arr3); 8 //输出结果: 9 [3,5,8]
当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,以后的值不会再调用执行函数。若是没有符合条件的元素返回 undefinedspa
1 var arr = [1,2,3,4,5,6,7]; 2 var newArr = arr.find(function(elem){ 3 return elem>5; 4 }); 5 console.log(newArr); 6 //输出结果 7 6
every()与filter()的区别是:后者会返回全部符合过滤条件的元素;前者会判断是否是数组中的全部元素都符合条件,而且返回的是布尔值code
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 var bol = arr.every(function(element){ 3 if(typeof element == 'string'){ 4 return element; 5 } 6 }) 7 console.log(bol); //false
every()与some()的区别是:前者要求全部元素都符合条件才返回true,后者要求只要有符合条件的就返回true对象
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 var bol = arr.some(function(element){ 3 if(typeof element == 'string'){ 4 return element; 5 } 6 }) 7 console.log(bol); //true
8.findindex() ES6数组新API,找到符合条件的索引并返回blog
1 var ages = [3, 10, 18, 20]; 2 3 function checkAdult(age) { 4 return age >= 18; 5 }
function(currentValue, index,arr)索引
参数currentValue:必需。当前元素element
index:可选。当前元素的索引回调函数
arr:可选.当前元素所属的数组对象