【发布时间】:2021-11-25 16:16:47
【问题描述】:
我很困惑为什么会收到错误,因为我传入了一个已定义且应该有长度的数组。然而,我不断收到“第 XXX 行的类型错误:无法读取未定义的属性(读取'长度')”
这是我正在处理的代码...
function getAllCombos(arr) {
// declare an array to hold results
let results = [];
// declare an innerfunction which takes a prefix and the original array passed in
function recurse(prefix, arr) {
// loop through the original array, our base case will be when the loop ends
for (let i = 0; i < arr.length; i++) {
// push the results of spreading the prefix into an array along with the current element both in an array
results.push([...prefix, arr[i]]);
// recursive case: now we build the prefix, we recurse and pass into our prefix parameter an array consisting of the prefix spread in, the current element being iterated on, and the original array sliced after our current element
recurse([...prefix, arr[i], arr.slice(i+1)])
}
}
// call the inner function with an empry prefix argument and the original array
recurse([], arr);
// return the results array
return results;
}
这里有一些测试用例...
console.log(getAllCombos(['a', 'b'])); // -> [['a','b'], ['a'], ['b'], []]
console.log(getAllCombos(['a', 'b', 'c']));
// -> [
// ['a', 'b', 'c'],
// ['a', 'b'],
// ['a', 'c'],
// ['a'],
// ['b', 'c'],
// ['b'],
// ['c'],
// [],
// ]
有人可以向我解释为什么即使我传入一个有长度的数组,我仍然会收到此错误消息吗?
感谢您的指点!
【问题讨论】:
-
function recurse(prefix, arr)接受两个参数,你传递一个:recurse([...prefix, arr[i], arr.slice(i+1)]) -
我能看到的是你有一个变量阴影。
arr在上层作用域和recurse函数中,在递归调用中,你永远不会通过上层作用域arr,因为你已经定义了内部作用域undefined。不要使用相同的名称。并通过 var 也 -
谢谢!你们俩!
标签: javascript recursion typeerror combinations