JS 数组方法总结

1、按是否改变原数组进行区分

1.1、不改变原数组

  • 追加元素
   //1、concat
    const arr1 = ['a', 'b', 'c', 'd', 'e'];
    const arr2 = arr1.concat('f'); // ['a', 'b', 'c', 'd', 'e', 'f']
    console.log(arr1); // ['a', 'b', 'c', 'd', 'e']
     //2、ES6扩展运算符...
    const arr1 = ['a', 'b', 'c', 'd', 'e'];
    const arr2 = [...arr1, 'f']; // ['a', 'b', 'c', 'd', 'e', 'f']  
    const arr3 = ['z', ...arr1]; // ['z', 'a', 'b', 'c', 'd', 'e']
  • 删除元素
   //1、filter
    const arr1 = ['a', 'b', 'c', 'd', 'e'];
    const arr2 = arr1.filter(a => a !== 'e'); // ['a', 'b', 'c', 'd']
     //2、slice
    const arr1 = ['a', 'b', 'c', 'd', 'e'];  
    const arr2 = arr1.slice(1, 5) // ['b', 'c', 'd', 'e']  
    const arr3 = arr1.slice(2) // ['c', 'd', 'e']
  • 替换元素
   //1、map
    const arr1 = ['a', 'b', 'c', 'd', 'e']  
    const arr2 = arr1.map(item => {  
        if(item === 'c') {
          item = 'CAT';
        }
        return item;
     }); // ['a', 'b', 'CAT', 'd', 'e']

1.2、改变原数组

  • 追加
    push & unshift
  • 删除
    pop & shift
  • 替换
    splice

2、数组遍历

  • forEach
var arr = [1,2,3,4,5,6,7,8];
// Uses the usual "for" loop to iterate
for(var i= 0, l = arr.length; i< l; i++){
console.log(arr[i]);
}
console.log("========================");
//Uses forEach to iterate
arr.forEach(function(item,index){
console.log(item);
});
  • reduce
    reduce(callback, initialValue)会传入两个变量。回调函数(callback)和初始值(initialValue)
    callback有两个参数pre,next.
    当不传入initialValue时,pre是数组的第一个值,next是第二个
    当传入initValue时,pre是initValue,next是数组的第一个参数
    注:initValue可以是任意类型的数据,不一定是数组中元素的类型。该方法并未对数组中元素进行操作,可看作遍历数组的一种。
var arr = ["apple","orange"];
//未传入
function noPassValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);
    return prev + " " +next;
  });
}
//传入一个对象
function passValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);  
    prev[next] = 1;
    return prev;
  },{});
}
console.log("No Additional parameter:",noPassValue());
console.log("----------------");
console.log("With {} as an additional parameter:",passValue());
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ES3数组方法 join() Array.join()方法将数组中所有元素都转化为字符串并连接在一起,返回最后生成...
    markdown阅读 773评论 1 8
  • 一、创建Array 创建数组主要有两种方法,第一种是使用数组构造函数,第二种是使用数组字面量表示法。 使用数组构造...
    JackfengGG阅读 959评论 0 51
  • 创建数组 arr.length--- title: js正则表达式categories: javascriptda...
    angelwgh阅读 1,407评论 0 2
  • 会改变自身的方法:## array.copyWithin(target, start [, end = this....
    mochase阅读 54,128评论 0 28
  • 第一章 系统 让一让让一让,让我把简历递进去。“别挤,急什么急,大家不和你一样啊,”旁边的胖子吼道。“对不起...
    阿里旺仔阅读 250评论 0 0