JavaScript数组的五个迭代方法的简单实例

时间:2022-08-11 18:22:56
<script>
//every()
var nums = [1,2,3,4,5];
var result = nums.every(function eve(item,index,array){
if (typeof(item) == "number"){
return true;
}
} );
console.log(result);//true,只有当该函数对每一项都返回true时,every()才会返回true //filter()
var nums2 = ['1',2,3,'str'];
var result2 = nums2.filter(function fil(item,index,array){
if(typeof(item) == "string"){
return true
}
});
console.log(result2);//返回 [该函数会返回true的项] 组成的数组 //forEach() var nums3 = [1,2,3,4,'qq','1'];
var log = "";
function fEach (item,index,array){
log += 'index['+index+']:'+ item +' ';
};
nums3.forEach(fEach);
console.log(log);
// nums3.forEach(alert);
// console.log(nums3); //map()
var nums4 = [1,'q','1',true];
var log2;
var result4 = nums4.map(function map(item,index,array){
log2 = 'index['+index+']:'+ item +' ';
return log2;//map()会返回每次函数调用的结果,作为一个数组。
})
console.log(result4); //some()
var nums5 = [1,2,3,4,true];
var result5 = nums5.some(function some(item,index,array){
if (typeof(item) == "boolean")
return true//只要函数对任意一项返回true,整个方法就会返回true
})
console.log(result5);
</script>