码迷,mamicode.com
首页 > 编程语言 > 详细

js中数组的方法

时间:2018-03-03 13:57:09      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:def   多个   code   csdn   res   each   uil   top   UI   

(参考网友例子)

一 js中不改变原数组的方法:

  • concat:连接多个数组,返回新的数组
  • join:将数组中所有元素以参数作为分隔符放入一个字符
  • slice:slice(start,end),返回选定元素    array.slice(start, end)

        var ary = [1,2,3,4,5];

        var res = ary.slice(1,3);

        console.log(ary); // [1,2,3,4,5]    console.log(res); // [2,3]

  • map,不改变原数组   ary.map(function(item,index,ary){}) item:每一项 index:索引 ary:当前数组
  • filter,不改变原数组   ary.filter(function(item,index,ary){}) item:每一项 index:索引 ary:当前数组
  • forEach  遍历,不改变原数组   ary.forEach(function(item,index,ary){}) item:每一项 index:索引 ary:当前数组

二 js中改变原数组的方法:

  • shift:将第一个元素删除并且返回删除元素,空即为undefined

       var ary = [‘a‘,‘b‘,‘c‘];

       var res = ary.shift();

       console.log(ary); // [‘b‘,‘c‘] console.log(res); // a

  • pop:删除最后一个并返回删除的元素

        var ary = [‘a‘,‘b‘,‘c‘];

        var res = ary.pop();

        console.log(ary); // [‘a‘,‘b‘]   console.log(res); // c

  • unshift:向数组开头添加元素,并返回新的长度

var ary = [‘a‘,‘b‘,‘c‘];

var res = ary.unshift(‘d‘,‘e‘);

console.log(ary); // ["d", "e", "a", "b", "c"]   console.log(res); // 5

  •  push:向数组末尾添加元素,并返回新的长度  

        var ary = [‘a‘,‘b‘,‘c‘];

        var res = ary.push(‘d‘,‘e‘,‘f‘);

        console.log(ary);   // ["a", "b", "c", "d", "e","f"] console.log(res); // 6

  •  reverse:颠倒数组顺序
  •  sort:对数组排序
  •  splice:splice(start,length,item)删,增,替换数组元素,返回被删除数组,无删除则不返回

         增加的功能

       ary.splice(n,0,x,......,y);

从数组的索引n开始,删除0项,在索引n的前边增加新的项,第三个参数开始都是用来填补删除的项目位置的

var ary = [1,2,3,4,5];
var res = ary.splice(1,0,6,7);//从索引值1开始,删除0项
console.log(ary);  // [1, 6, 7, 2, 3, 4, 5]
console.log(res);  // [] 删除0项,返回一个空数组

修改的功能
ary.splice(n,m,x);
从数组的索引n开始,删除m项,把x添加到索引n前边

var ary = [1,2,3,4,5];
var res = ary.splice(1,2,6,7);
console.log(ary);  // [1, 6, 7, 4, 5]
console.log(res);  // [2,3]
 

 

 

js中数组的方法

标签:def   多个   code   csdn   res   each   uil   top   UI   

原文地址:https://www.cnblogs.com/honghongwu/p/8481312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!