使用递归获取数组的长度,而无需访问其length属性。
下面的我的代码:
function getLength(array, count=0) {
if (array.length === 0){
return 0
}
else {
count ++;
array.pop()
return getLength(array, count)
}
return count;
}
// To check if you've completed the challenge, uncomment these console.logs!
console.log(getLength([1])); // -> 1
console.log(getLength([1, 2])); // -> 2
console.log(getLength([1, 2, 3, 4, 5])); // -> 5
console.log(getLength([], 0)); // -> 0
当我在第三个console.log上运行代码时:
console.log(getLength([1, 2]));
它返回0而不是2
我在做什么错?
///////////////////////////////////////////////// /////////////////////////
弄清楚了:
function getLength(array, count=0) {
if (array.length === 0){
return count
}
else {
count ++;
array.pop()
return getLength(array, count)
}
}
答案 0 :(得分:1)
您可以检查索引零处的项目是否存在。这仅适用于非稀疏数组。
function getLength(array) {
return 0 in array ? 1 + getLength(array.slice(1)) : 0;
}
console.log(getLength([1])); // 1
console.log(getLength([1, 2])); // 2
console.log(getLength([1, 2, 3, 4, 5])); // 5
console.log(getLength([], 0)); // 0
答案 1 :(得分:0)
另一个简单的解决方案(也不适用于稀疏数组)
const len1 = arr => arr.reduce(n => n + 1, 0)
还有一个相关但不那么简单的方法确实适用于稀疏数组:
const len2 = (arr) => Array.from(arr, _ => 1).reduce(n => n + 1, 0)