functionfactorialize(num) { if (num == null || num == undefined) { returnnull; } let type = typeof num; if (type != "number") { returnnull; } if (num == 0) { return1; } let result = 1; for (let i = 1; i <= num; ++i) { result *= i; } return result; }
阶乘递归版本:
1 2 3 4 5 6 7
functionfactorialize(num) { if (num == null || num == undefined) { returnnull; } let type = typeof num; if (type != "number") { returnnull; } if (num == 0) { return1; } return num * factorialize(num - 1); }
字符串反转的递归版本:
1 2 3 4 5 6 7 8 9 10
// 这个的递归模式就是最后一个加上前面剩余的反转. functionreverseString(str) { if (str == null || str == undefined) { return""; } let type = typeof str if (type != "string") { return""; } if (str.length == 1) { return str; } // 怎么表示前面剩余的字符串? 通过 substring 获取从开始index到结尾 index前闭后开区间的子串. let length = str.length; return str[length - 1] + reverseString(str.substring(0, length - 1)) }
找字符串中的最长单词:
1 2 3 4 5 6 7 8 9
functionfindLongestWordAmong(str) { let regex = /\w+/ig let lengthArr = str.split(' ') .map((value, index, arr) => { return value.length; }) .sort((a, b) => a < b); return lengthArr[0]; }