晴明的博客园 GitHub      CodePen      CodeWars     

[js] 简单遍历清晰层级对象字面量

#1

            function listToArray(list) {
                var array = [];
                for (var node = list; node; node = node.next) {
                    array.push(node.value);
                }
                return array;
            }

#2

            function listToArray(list) {
                return !list ? [] : [list.value].concat(listToArray(list.next));
            }

#3

            function listToArray(list) {
                var temp = [];
                while (list) {
                    temp.push(list.value);
                    list = list.next;
                }
                return temp;
            }

#4

            function listToArray(list) {
                var temp = [];
                if (list) {
                    temp.push(list.value);
                    return temp.concat(listToArray(list.next));
                } else {
                    return temp;
                }
            }

#test

            var list1 = {
                value: 1,
                next: {
                    value: 2,
                    next: {
                        value: 3,
                        next: null
                    }
                }
            };
            var list2 = {
                value: "foo",
                next: {
                    value: "bar",
                    next: null
                }
            };
            console.log(listToArray(list1));
            console.log(listToArray(list2));

 

posted @ 2016-03-19 11:57  晴明桑  阅读(297)  评论(0编辑  收藏  举报