我在 Eloquent Javascript 中尝试了与此特定练习相关的所有解决方案,但没有任何解决方案可以解决我的问题。
您可以看到arrayToList function here
我的问题是如何通过从头到尾循环而不是从头到尾循环来编写程序。
这是我的解决方案:
function arrayToList(arr) {
var entry = { value: null, rest: null}
for (var i = 0; i < arr.length; i++) {
if(entry.value == null)
entry.value = arr[i]
else{
entry.rest = arrayToList([arr[i]])
}
}
return entry
}
console.log(arrayToList([10,20]));
一切顺利。
Input - console.log(arrayToList([10, 20]));
output - { value: 10, rest: { value: 20, rest: null } }
但是下面的一个问题
Input - console.log(arrayToList([10, 20, 30]));
Actual output - { value: 10, rest: { value: 30, rest: null } }
Expected output - { value: 10,
rest: { value: 20, rest: { value: 30, rest: null } } }
我不知道如何递归调用,以便即使数组中有超过 2 个元素,它仍然能够创建列表结构
最佳答案
你已经很接近了。您需要在递归调用中传递数组的其余部分,例如
// Return object like {"value": 10, "rest": {"value": 20, "rest": null}}
function arrayToList0(arr) {
var entry = {};
// Check if there are any members in arr
if (arr.length) {
// If there are, add the value
entry.value = arr[0];
}
// If there are more entries, add them
if (arr.length > 1) {
// Call recursively without first element
entry.rest = arrayToList(arr.slice(1));
// Otherwise, add null
} else {
entry.rest = null;
}
return entry;
}
console.log(arrayToList([1,2,3]));
可以缩短为:
function arrayToList(arr) {
var entry = arr.length? {value:arr[0]} : {};
entry.rest = arr.length > 1? arrayToList(arr.slice(1)) : null;
return entry;
}
您没有说明如何处理稀疏数组,上面期望的是没有丢失元素的连续数组。对于稀疏数组,结果中会出现大量 value: undefined
。
关于javascript - Eloquent Javascript - ch4 - arraytoList - 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46540211/