vue(一)nodejs操作数组

常见方法,其中filter和map会改变数组

let array=[1,2,3,4,5];
// for (let index = 0; index < array.length; index++) {
//   const element = array[index];
//   console.log(element);
// }

// 1)let val of obj  遍历
// let obj={name:'huang',age:24};
// for(let val of Object.keys(obj)){
//   console.log(obj[val])
// }

// 2)filter 过滤
// let arr=array.filter(function(item){
//   return item>2&&item<5;
// })
// console.log(arr);

// 3)map 映射
// let arr = array.map(function(item){
//   // return item*3;
//   return `<li>${item}</li>`;    //``是ESC下的那个键
// })
// console.log(arr);
// console.log(arr.join(''));

// 4)includes查找元素,返回ture or false
// console.log(array.includes(5));  
// console.log(array.includes(55));

// 5)find返回找到的那一项,不会改变数组,找不到返回undefined
// let result = array.find(function(item,index){ 
//   // return item.toString().indexOf(4123)>-1;
//   return item.toString().indexOf(4)>-1;
// });
// console.log(result);

//6)some  找true  找到true后停止,返回true ,找不到返回false
//7)every 找false 找到false后停止,返回false
// let result = array.some(function(item,index){ 
//   // return item.toString().indexOf(4123)>-1;
//   return item.toString().indexOf(4)>-1;
// });
// console.log(result);

//8)reduce 返回的是叠加后的结果,原数组不发生变化
// 第一次循环prev代表数组的第一项,next是数组的第二项
// 第二次循环prev是undefined,next是数组的第三项
// let sum=array.reduce(function(prev,next,index,item){
//   // console.log(arguments);
//   console.log(prev,next);
//   return prev+next; //本次的返回值会作为下一次的prev
// })
// console.log('数组求和为:'+sum);

// let array2 = [{price:30,count:2},{price:30,count:3},{price:30,count:4}]
// let sum2 = array2.reduce(function(prev,next){
//   return prev+next.price*next.count;
// },0); //默认指定第一次的prev
// console.log(sum2);

// let array3=[[1,2,3],[4,5,6],[7,8,9]];
// let flat=array3.reduce(function(prev,next){
//   return prev.concat(next);
// });
// console.log(flat);

猜你喜欢

转载自blog.csdn.net/q975583865/article/details/84619024