ES6中有三个大而重要的数组方法 map,filter,reduce
作者:互联网
// map 方法,对数组进行循环操作 并传入一个新的数组 const movements = [200, 450, -400, 3000, -650, -130, 70, 1300]; const eurToUsd = 1.1; // const movementsUSD = movements.map(function (mov) { // return mov * eurToUsd; // }); const movementsUSD = movements.map(mov => mov * eurToUsd); console.log(movements); console.log(movementsUSD); const movementsUSDfor = []; for (const mov of movements) movementsUSDfor.push(mov * eurToUsd); console.log(movementsUSDfor); const movementsDescriptions = movements.map( (mov, i) => `Movement ${i + 1}: You ${mov > 0 ? 'deposited' : 'withdrew'} ${Math.abs( mov )}` );
// filter()过滤器 const movements = [200, 450, -400, 3000, -650, -130, 70, 1300]; // 也能使用三个参数 第一个数值,第二个索引,第三个数组本身 const deposits = movements.filter(function (mov, i, arr) { return mov > 0; // 不符合条件的将会被过滤,符合条件的进入新的数组 }); // 好处是可以链接其他方法,可混合字符串方法和数组方法 console.log(movements); console.log(deposits); const depositsFor = []; for (const mov of movements) if (mov > 0) depositsFor.push(mov); console.log(depositsFor); const withdrawals = movements.filter(mov => mov < 0); console.log(withdrawals);
标签:ES6,const,log,map,reduce,mov,console,movements 来源: https://www.cnblogs.com/heartY/p/16469826.html