javascript 几种循环比较

it2022-05-05  123

filter

var arr = [ {"name":"apple", "count": 2}, {"name":"orange", "count": 5}, {"name":"pear", "count": 3}, {"name":"orange", "count": 16}, ]; var newArr = arr.filter(function(item){ return item.name === "orange"; });

forEach为每个元素执行对应的方法  

arr.forEach(function(item,index){ console.log(item); });

map()对数组的每个元素进行一定操作(映射)后,会返回一个新的数组,

var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}]; function getNewArr(){       return oldArr.map(function(item,index){    item.full_name = [item.first_name,item.last_name].join(" ");    return item;  });   }console.log(getNewArr());

reduce()可以实现一个累加器的功能,将数组的每个值(从左到右)将其降低到一个值

var arr = ["apple","orange"]; arr.reduce(function(prev,next){ console.log("prev:",prev); console.log("next:",next); return prev + " " +next; });

  

转载于:https://www.cnblogs.com/haigui-zx/p/7382015.html


最新回复(0)