oxspirt

var n = {1:100, 2:101, 3:102, 4:103};

怎么获取这个对象n的长度呢?

 

方法一:

function getLength(obj){

  var count = 0;
  for(var i in n){
     count++;
  }

  return count;  
}

//改进  加上一个hasOwnProperty判断过滤下原型中的属性就比较安全了

function getLength(obj){

  var count = 0;
  for(var i in n){

    if(n.hasOwnProperty(i)){
                count++;

           }
  }

  return count;  
}

方法二: //无需考虑hasOwnProperty的情况下

function getLength(obj){

  return Object.key(n).length; 
}

 

分类:

技术点:

相关文章:

  • 2022-01-30
  • 2022-12-23
  • 2021-09-19
  • 2022-12-23
  • 2021-08-06
  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
猜你喜欢
  • 2022-01-05
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案