知识点
- 递归思路
Array.from
new Array
参数和Array.of
的区别- 数组的
keys()
方法 - 数组
map
方法对空对象的处理
题目
完成arrWithoutLoop
函数,它会被传入一个整数n
作为参数,返回一个长度为n
的数组,数组中每个元素的值等于它的下标。arrWithoutLoop
中不能使用循环控制结构。
实现
首先想到了用Array.from
方法,原来用它来填充数组,它接受两个参数,第一个参数是一个类似数组或可迭代对象,第二个参数是对新数组每个元素执行的回调函数
所以我们可以通过构造一个类数组对象{length: n}
来生成一个数组,或者也可以直接构造数组(new Array(n)),生成一个n个空对象的新数组,然后通过Array.from
的第二个参数生成想要的元素:
const arrWithoutLoop = (n) => Array.from({ length: n }, (value, key) => key)
为什么不能用map
呢?因为map
/forEach
等都会跳过数组中的空对象
第二种方法
不让使用循环控制结构,可以使用递归来实现,递归的思路不难,从n-1
开始插入,插入一个之后n-1
,继续调用,直到n===1
结束
要注意的是,如果n为0
时需要特殊处理一下
const arrWithoutLoop = (n) => {
if(n === 0) {
return []
}
let result = [];
result.unshift(n - 1);
if (n === 1) {
return result
} else {
return arrWithoutLoop(n - 1).concat(result)
}
};
也可以换一种写法:
const arrWithoutLoop = (n, result = []) => {
if (n === 0) {
return [];
}
result.unshift(n - 1);
if (n === 1) {
return result;
} else {
return arrWithoutLoop(n - 1, result)
}
};
另外一种方法
受到讨论区的启发,看到还有一种很巧妙的方法,现在要插入的是数组的下标,所以想到可以直接使用数组的keys
方法
ES6提供三个新的方法——entries()
,keys()
和values()
——用于遍历数组。它们都返回一个遍历器对象,可以用for...of
循环进行遍历,唯一的区别是keys()
是对键名的遍历、values()
是对键值的遍历,entries()
是对键值对的遍历。
返回的迭代器对象我们可以通过for...of
循环取值,也可以使用解构赋值的方法取值
const arrWithoutLoop = (n) => [...new Array(n).keys()];