将字符串翻转:
function reverseString(str) { //法一: /* let arr=[]; for(let i=0;i<str.length;i++){ arr.unshift(str[i]); } //console.log(arr);//[ 'o', 'l', 'l', 'e', 'h' ] str=''; for(let i=0;i<arr.length;i++){ str=str+arr[i]; } //console.log(str);//olleh return str; */ //法二: let reversedStr = ""; for (let i = str.length - 1; i >= 0; i--) { reversedStr += str[i]; } //法三: /* return str .split("") .reverse() .join(""); */ return reversedStr; } //调用: console.log(reverseString("hello")); //ollehView Code
求整数的阶乘:
只有大于或等于零的整数才能计算阶乘,阶乘是所有小于或等于n的正整数的乘积,简写为n!,例如:5!=1 * 2 * 3 * 4 * 5 = 120
function factorialize(num) { //法一: /*let product = 1; for (let i = 2; i <= num; i++) { product *= i; } return product;*/ //法二: /*if (num === 0) { return 1; } return num * factorialize(num - 1); */ //法三: return num < 0 ? 1 : new Array(num) .fill(undefined) .reduce((product, _, index) => product * (index + 1), 1); } //法四: /*function factorialize(num, factorial = 1) { if (num === 0) { return factorial; } else { return factorialize(num - 1, factorial * num); } }*/ console.log(factorialize(5)); //120View Code
查找字符串中最长的单词,返回其长度:
function findLongestWordLength(str) { //法一: //return Math.max(...str.split(" ").map(word => word.length)); //法二: //return str.split(' ').reduce(function(longest, word) {return Math.max(longest, word.length)}, 0); //法三: /*let words = str.split(' '); let maxLength = 0; for (let i = 0; i < words.length; i++) { if (words[i].length > maxLength) { maxLength = words[i].length; } } return maxLength;*/ //法四: /*const words = str.split(" "); if (words.length == 1) { return words[0].length; } return Math.max(words[0].length,findLongestWordLength(words.slice(1).join(" ")));*/ //法五: let longestLength = 0; let currentLength = 0; for (let i = 0; i < str.length; i++) { if (str[i] === " ") { if (currentLength > longestLength) longestLength = currentLength; currentLength = 0; } else { currentLength++; } } if (currentLength > longestLength) { longestLength = currentLength; } return longestLength; } //调用: console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog")); //6View Code
查找数组中最大的数字:
标签:脚本,return,words,currentLength,基础,length,算法,let,str From: https://www.cnblogs.com/168-h/p/16733607.html