【问题标题】:i need to loook for amount of properties in object , can not find the mistake我需要查找对象中的属性数量,找不到错误
【发布时间】:2021-04-12 10:12:30
【问题描述】:
function propsCount(){ 
       let mentor = { 
          course: "JS fundamental", 
          duration: 3,
          direction: "web-development"
       };

       console.log(Object.keys(mentor).length);
       console.log(propsCount(mentor));
}

【问题讨论】:

  • 这里可能有很多问题。请你分享一下你想如何使用这个函数以及它应该输出什么的例子
  • 好吧,你没有调用你的函数。您是从内部而不是外部调用它,所以可能就是这样。

标签: javascript arrays function


【解决方案1】:

我不确定您要完成什么,但我编写了这段代码,也许是对的

function propsCount(){ 
        let mentor = { 
            course: "JS fundamental", 
            duration: 3,
            direction: "web-development"
         };

        return Object.keys(mentor).length;
    }

   console.log(propsCount());

该函数创建一个导师对象,然后返回该对象的长度。然后console.log返回长度

【讨论】:

    【解决方案2】:
    function propsCount(){ 
           let mentor = { 
              course: "JS fundamental", 
              duration: 3,
              direction: "web-development"
           };
    
           console.log(Object.keys(mentor).length);
          // console.log(propsCount(mentor)); this function is recursive 
    }
    

    console.log(propsCount(mentor)); 这个控制台函数是递归的,所以它永远不会结束,所以它会给你maximum stack 的错误。尝试 rmove 一切正常。使用 return 来获取它的属性计数。

    试试这个:

    function propsCount(obj){ 
         return Object.keys(obj).length;
    }
    
     var propertyLength = propsCount({course: "JS fundamental", duration: 3,direction: "web-development"});
    // or 
    //let mentor = { 
    //          course: "JS fundamental", 
    //          duration: 3,
    //          direction: "web-development"
    //       };
    // var propertyLength = propsCount(mentor);
    // Or in ES6
    // const propsCount = obj => Object.keys(obj).length; 
    console.log(propertyLength);
    

    【讨论】:

    • 或者在 ES6 中 const propsCount = obj => Object.keys(obj).length;
    猜你喜欢
    • 1970-01-01
    • 2018-03-06
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多