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]
every()与filter()的区别是:后者会返回所有符合过滤条件的元素;前者会判断是不是数组中的所有元素都符合条件,并且返回的是布尔值
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
7.findindex() es6数组新api,找到符合条件的索引并返回
1 var ages = [3, 10, 18, 20]; 2 3 function checkadult(age) { 4 return age >= 18; 5 }
function(currentvalue, index,arr)
参数currentvalue:必需。当前元素
index:可选。当前元素的索引
arr:可选.当前元素所属的数组对象
如对本文有疑问, 点击进行留言回复!!
Unable to load script from assets‘index.android.bundle‘.Make sure your bundle is packaged correctly
网友评论