<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>JS 1, 11, 21, 1211, 111221 找规律</title> </head> <body> <script> //群友(大卡车)实现的方法 function countNum(str) { let Str = str.toString(); let Strs = Str.split(""); let returnStr = []; let position = 0; Strs.forEach((e, i) => { if (returnStr[position]) { if (e === returnStr[position][0]) { returnStr[position]+=e } else { returnStr[++position] = e; } } else { returnStr[position]=e } }) return returnStr.map(e => `${e.length}${e[0]}`).join(""); } //群主实现的方法 function countAndSay(n) { var last = '1' if (n <= 1) { return last } for (var i = 1; i < n; i++) { var str = last var ret = [] for (var s = 0, sn = str.length; s < sn; s++) { var a = str[s] if (a === ret[ret.length - 1]) { ret[ret.length - 2]++ } else { ret.push(1, a) //量词在前,名词在后 } } last = ret.join('') } return last } console.info(countNum(countNum(countNum(countNum(1))))); console.info(countAndSay(5)) </script> </body> </html>
效果图: