如代码, 分别实现 diyTrim 及 removeRepetition 函数, 并跑通代码中的测试用例.
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="utf-8" />
- <title>
- JS 里的居民们 3
- </title>
- </head>
- <body>
- <script>
- /*
- 实现一个字符串头尾去除空格的函数
- 注意需要去除的空格, 包括全角, 半角空格
- 暂时不需要学习和使用正则表达式的方式
- */
- function diyTrim(str) {
- // 遍历一下每个字符前后是否为空格, 是的话进行切割字符串, 直到没有空格, 结束循环.
- for (i = 0; i < str.length; i++) {
- if (str[0] == "" || str[0] == " ") {
- str = str.slice(1);
- } else if (str[str.length - 1] == "" || str[str.length - 1] == " ") {
- str = str.slice(0, str.length - 2);
- } else {
- break;
- }
- }
- return str;
- }
- // 测试用例
- console.log(diyTrim('a f b')); // ->a f b
- console.log(diyTrim('ffdaf')); // ->ffdaf
- console.log(diyTrim('1')); // ->1
- console.log(diyTrim('f')); // ->f
- console.log(diyTrim('a f b')); // ->a f b
- console.log(diyTrim(' ')); // ->
- console.log(diyTrim(' ')); // ->
- console.log(diyTrim('')); // ->
- /*
- 去掉字符串 str 中, 连续重复的地方
- */
- function removeRepetition(str) {
- var result = "";
- for (i = 0, len = str.length; i < len; i++) { // 定义 len, 每次循环都会改变长度
- if (str[0] == str[1]) { // 判断前后是否一致
- str = str.slice(1); // 记得赋值给 str, 不然就是原来的数组.
- } else {
- result = result + str[0]; // 存入不重复的值, 并且要往后继续移一个
- str = str.slice(1);
- }
- }
- return result;
- }
- // 测试用例
- console.log(removeRepetition("aaa")); // ->a
- console.log(removeRepetition("abbba")); // ->aba
- console.log(removeRepetition("aabbaabb")); // ->abab
- console.log(removeRepetition("")); // ->
- console.log(removeRepetition("abc")); // ->abc
- </script>
- </body>
- </HTML>
来源: http://www.bubuko.com/infodetail-2873653.html