归档 标签 友链 关于

JavaScript Object / Array 递归遍历

function traverseArr(arr) {
    for (var index in arr) {
        console.log('///');
        console.log(index + ':');
        console.log(arr[index]);
        if (Object.prototype.toString.call(arr[index]) == '[object Object]') {
            traverseObj(arr[index]);
        }
    }
}

function traverseObj(obj) {
    for (var key in obj) {
        console.log('---');
        console.log(Object.prototype.toString.call(obj[key]));
        console.log(key + ':');
        console.log(obj[key]);
        if (Object.prototype.toString.call(obj[key]) == '[object Object]') {
            traverseObj(obj[key]);
        }
        if (Object.prototype.toString.call(obj[key]) == '[object Array]') {
            traverseArr(obj[key]);
        }
    }
}

用法:

traverseObj(obj); // 遍历对象
traverseArr(arr); // 遍历数组

· 转载请注明 https://tangkaichuan.cn/js-object-recursive-traversal/