Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Created July 17, 2014 15:44
Show Gist options
  • Save jikeytang/27ddcd9735b798a0b62e to your computer and use it in GitHub Desktop.
Save jikeytang/27ddcd9735b798a0b62e to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140718-题目1
请把一组有规律的单词拼接起来,规则为:
前一个单词的结尾应该与下一个单词的首字母相同。
如: aloha, dog, arachnid, gopher, tiger, rat
结果为:aloha-arachnid-dog-gopher-rat-tiger.
PS:
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
// you code
```
2. 粘贴代码时请使用shift+tab,缩进前面的空白。
@bhnddowinf
Copy link

我很少用 js写程式,各位常用 js,一定可以再优化

    <script>

        var arr =  ['aloha', 'dog', 'arachnid', 'gopher', 'tiger', 'rat'];
        // 印出数组
        document.write('<br>数组:');
        for (var i =0 ;i<arr.length;i++) {
            document.write(arr[i]+', ');
        }
        document.write('<br>');

        var txt1="";

        var fun = function(arr1) {//递归方式计算
            arr_length = arr1.length;

            // 印出数组
            //document.write('<br>数组:');
            //for (var i =0 ;i<arr_length;i++) {
            //    document.write(arr1[i]+', ');
            //}
            //document.write('<br>arr.length : ' + arr.length + ', 比对字符串:' + arr1[0]);

            //document.write('->'+arr1[0]);    // 印出讯息予用户
            txt1 = txt1 + '-' + arr1[0];
            str_x = right(arr1[0],1);

            for (var i =1 ;i<arr_length;i++){
                str_y = left(arr1[i],1);

                if (str_x==str_y){
                   // document.write ('<br>'+i+'  '+arr1[i]+'  : '+str_x+' '+ str_y);
                   // document.write('<br>'+i+'-'+arr1[i]);    // 印出讯息予用户
                    Str_temp = arr1[i]    // 找到字符串的元素,移动到此数组的第1个
                    arr1.splice(0,1);      // 此数组 移除 第一个元素
                    arr1.splice(i-1,1);      // 此数组,找到字符串的元素, 移除
                    arr1.unshift(Str_temp);  //此数组,加入第一个是找到的字符串
                    return ( fun(arr1));    // 递归
                }
            }

           document.write ('<br>=>'+txt1.substring(1,txt1.length));

        }

        fun(arr);


        function left(str, num)
        {
            return str.substring(0,num)
        }

        function right(str, num)
        {
            return str.substring(str.length-num,str.length)
        }
    </script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment