嵌套列表到数组

时间:2016-11-14 15:30:00

标签: javascript arrays nested-lists

我正在努力使用这个指示我从嵌套列表中创建数组的kata。我可以找到有关如何使用Java执行此操作的解释,但这对我来说仍然有点混乱。

这是我到目前为止所得到的......



function listToArray(list) {
  var listArray = [];
  for (var i = 0; i < list.length; i++) {
    listArray[i] = list.value(i);
  };
  return listArray;
};
&#13;
&#13;
&#13;

测试案例......

&#13;
&#13;
var list1 = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
var list2 = {value: "foo", next: {value: "bar", next: null}};

Test.assertSimilar(listToArray(list1), [1, 2, 3]);
Test.assertSimilar(listToArray(list2), ["foo", "bar"]);
&#13;
&#13;
&#13;

感谢您的帮助!

4 个答案:

答案 0 :(得分:4)

这只是一个链表指针追逐:

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

答案 1 :(得分:1)

使用递归

&#13;
&#13;
function listToArray(list) {
  var res = [];
  Object.keys(list).forEach(function(k) {
    if (typeof list[k] == 'object' && list[k] !== null)
      [].push.apply(res, listToArray(list[k]));
    else if (list[k] !== null)
      res.push(list[k]);
  });
  return res;
};

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));
&#13;
&#13;
&#13;

答案 2 :(得分:1)

使用递归的另一种解决方案

var list1 = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
var list2 = {value: "foo", next: {value: "bar", next: null}};

function convertToArray(list, result) {
  result.push(list.value);
  list.next && convertToArray(list.next,result);
  return result;
}

console.log(convertToArray(list1,[]));
console.log(convertToArray(list2,[]));

答案 3 :(得分:1)

您必须深入挖掘对象,直到达到null点。

var list1 = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
var list2 = {value: "foo", next: {value: "bar", next: null}};

function listToArray(list) {
  var curr = list, arr = [];
  while (curr != null) {
    arr.push(curr.value);
    curr = curr.next;
  }
  return arr;
}

console.log(listToArray(list1));
console.log(listToArray(list2));