[英]Javascript Accessing nested objects in lists i
I am pretty brand new to coding so please excuse me if this is too much of a basic question. 我对编码非常陌生,因此如果这是一个基本问题,请原谅。 I am going through the challenges on codewars.com to try to increase my coding aptitude.
我正在通过codewars.com上的挑战来尝试提高我的编码能力。 The one I am currently working on has the following prompt:
我目前正在处理的程序具有以下提示:
Lists are data structures composed of nested objects, each containing a single value and a reference to the next object.Write a function listToArray (or list_to_array in Python) that converts a list to an array. 列表是由嵌套对象组成的数据结构,每个对象都包含一个值和对下一个对象的引用。编写一个函数listToArray(或Python中的list_to_array),将列表转换为数组。
The issue I am having is with the lists. 我遇到的问题是列表。 They are nested and keep nesting.
它们被嵌套并保持嵌套。 My question is how do I access the value for each object if it is nested further and further?
我的问题是,如果嵌套的对象越来越远,如何访问每个对象的值? I believe if I can figure out how to access the values I should be able to create the array pretty easily.
我相信,如果我能弄清楚如何访问这些值,我应该可以很容易地创建数组。 Thanks in advance!
提前致谢!
List example: {value: 1, next: {value: 2, next: {value: 3, next: null}}}
列出示例:
{value: 1, next: {value: 2, next: {value: 3, next: null}}}
Desired final result: [1, 2, 3]
所需的最终结果:
[1, 2, 3]
What I have thus far: 到目前为止,我有:
function listToArray(list) { var arr; for (var i in list) { arr += list [i]; i++; } // return arr; } var list1 = {value: 1, next: {value: 2, next: {value: 3, next: null}}}; listToArray(list1)
With lists, you usually use while loops to iterate. 对于列表,通常使用while循环进行迭代。
function listToArray(list) {
var arr = [];
while(list !== null) {
arr.push(list.value);
list = list.next;
}
return arr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.