js操作数组的一些方法

刺骨的言语ヽ痛彻心扉 2024-03-30 14:12 200阅读 0赞
定义一个数组
  1. var numbers= ['1','2','3','4','5'];
1、删除尾部元素
  1. this.numbers.pop();
2、尾部添加元素
  1. this.numbers.push('6');
3、删除首部元素
  1. this.numbers.shift();
4、首部添加元素
  1. this.numbers.unshift('0');
5、第一个参数为起始位置 ,第二个参数为删除个数
  1. this.numbers.splice(1,3);
6、排序
  1. this.numbers.sort();
7、反转
  1. this.numbers.reverse();
8、过滤
  1. let result = numbers.filter(function (number){
  2. return number > 4
  3. });
9、对每条数据乘2
  1. let result2 = numbers.map(function (number){
  2. return number * 2;
  3. });
10、求和
  1. let total = numbers.reduce(function (preValue,value){
  2. return preValue + value;
  3. },0);

参数1:回调函数 这个函数有两个参数 参数1是上一次循环此方法返回的值 参数2是当前循环的元素
参数2: 第一次调用时 回调函数的第一个参数的默认值
return preValue + value; 作用: 将数组中的全部值相加 返回一个数字

发表评论

表情:
评论列表 (有 0 条评论,200人围观)

还没有评论,来说两句吧...

相关阅读