var arr = ["first","second","third","fourth",100,200,300]; for(var i = 0; i < arr.length;i++){ console.log(arr[i]); } //输出: first second third fourth 100 200 300
var arr = ["first","second",‘third‘ ,"fourth",100,200,300]; for(var i in arr){ console.log(arr[i] +‘/‘ + i); } //输出结果为: first/0 second/1 third/2 fourth/3 100/4 200/5 300/6
var arr = ["first","second",‘third‘ ,"fourth",1,2,3]; for(var item of arr){ console.log(item); } //输出结果: first second third fourth 1 2 3
虽然for… in 、 for… of 都能够变历数组,但是两者还是有很大区别的,先说结论:
两者的主要区别在于他们的迭代方式
var arr = ["first","second","third","fourth",100,200,300]; //element 表示arr的单元项,index 表示arr单元项对应的索引值 arr.forEach(function(element,index){ console.log(element + ‘/‘ + index); }) //输出结果: first/0 second/1 third/2 fourth/3 100/4 200/5 300/6
注意:未赋值的值是不会在foreach循环迭代的,但是手动赋值为undefined的元素是会被列出的
var arr = ["first","second",‘third‘ ,"fourth"]; var arr2 = arr.map(function(item){ return item.toUpperCase(); }) console.log(arr2); //输出: [FIRST,SECOND,THIRD, FOURTH]
var arr = ["first","second",‘third‘ ,"fourth",100,200,300]; var arr3 = arr.filter(function(item){ if(typeof item == ‘number‘){ return item; } }) console.log(arr3); //输出结果: [100,200,300]
every()与filter()的区别是:后者会返回所有符合过滤条件的元素;前者会判断是不是数组中的所有元素都符合条件,并且返回的是布尔值
var arr = ["first","second",‘third‘ ,"fourth",100,200,300]; var bol = arr.every(function(element){ if(typeof element == ‘string‘){ return element; } }) console.log(bol); //false
every()与some()的区别是:前者要求所有元素都符合条件才返回true,后者要求只要有符合条件的就返回true
var arr = ["first","second",‘third‘ ,"fourth",100,200,300]; var bol = arr.some(function(element){ if(typeof element == ‘string‘){ return element; } }) console.log(bol); //true
原文:https://www.cnblogs.com/zhuyan0000/p/10847429.html