Last active
July 3, 2018 09:54
-
-
Save langjt/e5f1a366b0d87198a1dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 有一个数n,不用for/while循环,怎么返回[1,2,3,...,n]这样一个数组 */ | |
// 方法一:递归 | |
function recursionLoop(n) { | |
var arr = []; | |
return (function () { | |
arr.unshift(n); // 入队 | |
n--; | |
if (n != 0) { | |
arguments.callee(); // 递归 | |
} | |
return arr; | |
})(); | |
} | |
// 方法二:string.replace | |
function replaceLoop(n) { | |
var arr = []; | |
arr.length = n+1; | |
var str = arr.join('a'); // 这里可以使用任意\w | |
arr.length = 0; // 清空数组 | |
str.replace(/a/g, function () { | |
arr.unshift(n--); // 入队 | |
}); | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment