如何循环更高阶函数?

时间:2016-10-24 05:34:30

标签: jquery arrays

data.forEach(function (object, index) {

    console.debug(object.output);
    //this consists of array object like below
    //how to loop through these using higher order function so that I don't have to use for loop

    [0]{"id": "453", "name":"keren"},
    [1]{"id": "453", "name":"amy"},
    [2]{"id": "453", "name":"samta"}

我得到的错误说,object.output不是一个函数。 我更喜欢高阶函数的原因是避免嵌套for循环获取数组的长度然后循环遍历主数组中的嵌套数组。

即使我使用传统的for循环,我也无法获得object.output的长度。

这是记录在内的内容:data.forEach(function (object, index) {....}

enter image description here

现在,我如何遍历每个输出对象?

根据Geeky回答编辑:

data.forEach(function (object, index) {
    Object.keys(object).forEach(function (key){

        if (typeof object[key] == 'object') {
            console.debug(object[key]);
            //how to iterate through each object here?
            object[key].forEach(function(x){
            console.debug(x);
            });
        }

    });
});

1 个答案:

答案 0 :(得分:1)

检查以下代码段



var arr=[ {"id": "453", "name":"keren"}
            ,{"id": "453", "name":"amy"}
            ,{"id": "453", "name":"samta"}
            ]

var object={"output":arr}
Traverse(object);

function Traverse(object){
Object.keys(object).forEach(function (key){
    console.log(object[key]);
    if(typeof(object[key])==="object")
           Traverse(object[key]);
         
});
}




希望有所帮助