js不用for循環生成0-10的數組方法,使用遞歸方法

1、使用遞歸方法

let arr = []
function addNum(num){
    if (num < 10) {
		arr.push(num)
		addNum(++num)
	} else {
		console.log(arr)
	}
}
addNum(0)

2、Array.apply()

let arr = Array.apply(null, {length: 10}).map((item, index) => {
	return index
})
console.log(arr)

3、Array.from()

let arr = Array.from({length: 10}).map((item, index) => {
	return index
})
console.log(arr)

4、Array.prototype.fill

let arr = new Array(10).fill(1).map((item, index) => {
	return index
})
console.log(arr)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章