zoukankan      html  css  js  c++  java
  • js实现以最简单的方式将数组元素添加到对象中的方法(给数组中元素添加属性)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    //如题,通常做法就是循环数组,最后在添加length属性,如:
     
      
    var obj = {};
     var pushArr = [11,22,33,44,55,66];
     for(var i=0;i<pushArr.length;i++) {
      obj[i] = pushArr[i];
     }
     obj.length = pushArr.length;
     
     console.log(obj); //{0:11,1:22,2:33,3:44,4:55,5:66,length:6}

    简单方法:

    1
    2
    3
    4
    5
    6
    7
    8
    //js将数组元素添加到对象中(或 数组转换成对象)有个小技巧:
     
    var obj = {};
    [].push.apply(obj,[11,22,33,44,55,66]);
     
    console.log(obj); //{0:11,1:22,2:33,3:44,4:55,5:66,length:6}
     
    由于obj是个对象没有像数组的push()方法,所以利用数组的push()以及apply()的特性来将数组作用于pus
  • 相关阅读:
    《POJ-2369》
    《1402
    《2018 Multi-University Training Contest 8》
    《HDU
    循环串
    模拟赛 数根 题解
    备份
    关于带删除线性基
    论OIer谈恋爱的必要性
    某计数题题解
  • 原文地址:https://www.cnblogs.com/Ao-min/p/14012368.html
Copyright © 2011-2022 走看看