数组遍历,对象遍历

数组的遍历

1.forEach

arr[].forEach(function(value,index,array) { } )

  • 参数:value是数组中的当前项,index是当前项的索引,array原型数组
  • 数组中有几项,那么传递进去的匿名回调函数就需要执行几次
  • 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以通过数组的索引来修改原来的数组
//foreach方法
    var arr = [12,23,24,42,1];
    var res = arr.forEach(function (item,index,input) {
     input[index] = item*10;
    })
    console.log(res);//-->undefined;
    console.log(arr);//-->[120,230,240,420,10]; 通过数组索引改变了原数组
//for方法
    var arr = [12,23,24,42,1];
    for(var i=0;i<arr.length;i++){
      arr[i] = arr[i] * 10;
    }
    console.log(arr);//-->[120,230,240,420,10]

2.map

arr[].map(function(value,index,array){ })

  • 参数:value数组中的当前项,index当前项的索引,array原始数组
    与foreach不一样的是,map的回调函数支持return返回值,
    并不影响原来的数组,只是把源数组克隆一份,把克隆的这一份的数组中的对影像改变了
    var arr = [12,23,24,42,1];
    var res = arr.map(function (item,index,input) {
     return item*10;
    })
    console.log(res);//-->[120,230,240,420,10]; 原数组拷贝了一份,并进行了修改
    console.log(arr);//-->[12,23,24,42,1]; 原数组并未发生变化

3.$.each

$.each(arr, function(index,value) {} )
参数: arr要遍历的数组,index当前像的索引,value数组中的当前项

    var arr = [12,23,24,42,1];
    var res = $.each(arr,function(index,value){
      arr[index] = value * 10;
    })
    console.log(arr); // [120, 230, 240, 420, 10]
    console.log(res); // [120, 230, 240, 420, 10]

对象的遍历

1.for in

主要用于遍历对象的可枚举属性,包括自有属性、继承自原型的属性

    var obj = {"name":"tom","sex":"male"};
    //增加不可枚举的属性age 
    Object.defineProperty(obj, "age", {value:"18", enumerable:false});
    //通过原型链增加属性,为一个函数
    Object.prototype.protoPer1 = function(){
      console.log("name is tom");
    };
    //通过原型链增加属性,为一个整型值2
    Object.prototype.protoPer2 = 2;
    for(var a in obj){
      console.log(a + ":" + obj[a]);
    }

Enumerable表示能否通过for-in循环返回属性
输出:

在这里插入图片描述

2.Object.keys(obj) \ Object.values(obj)

   var obj = {
    id:1,
    name:'zhangsan',
    age:18
    }
    console.log(Object.keys(obj)); //["id", "name", "age"]
    console.log(Object.values(obj)); //[1, "zhangsan", 18]

//遍历对象

    var obj = {
    id:1,
    name:'zhangsan',
    age:18
    }
    Object.keys(obj).forEach(function(key){
      console.log(obj);  
      console.log(key);
      console.log(obj[key]);
    })

输出:

在这里插入图片描述

3.使用Object.getOwnPropertyNames(obj)

    var obj = {
            id:1,
            name:'zhangsan',
            age:18
    }
    Object.getOwnPropertyNames(obj).forEach(function(key){
        console.log(key+ '---'+obj[key])
    })

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43553067/article/details/88861839