---
title: "JS 1, 11, 21, 1211, 111221 找规律"
author: "onestopweb"
date: "2017-04-07T10:15:03Z"
tags: ["1", "11", "21"]
categories: ["Web前端"]
slug: "js-1-11-21-1211-111221"
draft: false
lastmod: "2017-04-07T10:17:14Z"
id: 2367750
url: "https://onestopweb.iteye.com/blog/2367750"
---

```
<!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>
```

 

效果图：  
![](http://dl2.iteye.com/upload/attachment/0124/1946/de4359d7-b245-336d-af88-7e649d9b5f06.png)