[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));