任務18-數組、字符串、數學函數

問答題

  • 數組方法里push、pop、shift、unshift、join、split分別是什么作用。(*)

    答:
    push:給數組的最后一位添加一個元素。

    Paste_Image.png

    pop:將數組最后一位元素刪除。

    Paste_Image.png

    shift:去除數組中的第一位元素。


    Paste_Image.png

    unshift:在數組第一位添加一個元素。

    Paste_Image.png

    join:把數組元素用給的參數作為連接符連接成字符串,不會修改原來的數組。


    Paste_Image.png

    split:一個字符串分割成字符串數組,不會修改原來的數組。


    Paste_Image.png

代碼題

數組

  1. 用 splice 實現 push、pop、shift、unshift方法 (***)


    Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png
  1. 使用數組拼接出如下字符串 (***)

    var prod = {
        name: '女裝',
        styles: ['短款', '冬季', '春裝']
    };
    function getTpl(data){
    //todo...
    };
    var result = getTplStr(prod);  //result為下面的字符串
    
    var prod = {
       name: '女裝',
       styles: ['短款', '冬季', '春裝']
    };
    
    function getTplStr(data) {
    
    var html = [];
    html.push('<dl class="product">'+'\n');
    html.push(' <dt>'+data.name+'</dt>'+'\n');
    for(var i = 0; i<data.styles.length;i++){
        html.push(' <dd>'+data.styles[i]+'</dd>'+'\n');
    }
    html.push('<dl>');
    
    return html.join('');
    
    };
    var result = getTplStr(prod);
    console.log(result);
    
  2. 寫一個find函數,實現下面的功能 (***)

    var arr = [ "test", 2, 1.5, false ]
    find(arr, "test") // 0
    find(arr, 2) // 1
    find(arr, 0) // -1
    
    var arr = ["test", 2, 1.5, false];
    function find(arr,vl){
    var result = arr.indexOf(vl);
    return result;
    }
        
    find(arr, "test");// 0
    find(arr, 2); // 1
    find(arr, 0);// -1
    
  3. 寫一個函數filterNumeric,把數組 arr 中的數字過濾出來賦值給新數組newarr, 原數組arr不

    arr = ["a", "b", 1, 3, 5, "b", 2];
    newarr = filterNumeric(arr);  //   [1,3,5,2]
    
    arr = ["a", "b", 1, 3, 5, "b", 2];
    function filterNumeric(arrayName){
    return arrayName.filter(function(e){
        return typeof e === 'number';
    })
    }
    
    newarr = filterNumeric(arr);  //   [1,3,5,2]
    
    Paste_Image.png
  4. 對象obj有個className屬性,里面的值為的是空格分割的字符串(和html元素的class特性類似),寫addClass、removeClass函數,有如下功能:(****)

    var obj = {
      className: 'open menu'
    }
    addClass(obj, 'new') // obj.className='open menu new'
    addClass(obj, 'open')  // 因為open已經存在,所以不會再次添加open
    addClass(obj, 'me') // me不存在,所以 obj.className變為'open menu new me'
    console.log(obj.className)  // "open menu new me"
    
    removeClass(obj, 'open') // 去掉obj.className里面的 open,變成'menu new me'
    removeClass(obj, 'blabla')  // 因為blabla不存在,所以此操作無任何影響
    
    
        var obj = {
        className: 'open menu'
    }
    addClass(obj, 'new') // obj.className='open menu new'
    addClass(obj, 'open') // 因為open已經存在,所以不會再次添加open
    addClass(obj, 'me') // me不存在,所以 obj.className變為'open menu new me'
    console.log(obj.className) // "open menu new me"
    
    removeClass(obj, 'open') // 去掉obj.className里面的 open,變成'menu new me'
    removeClass(obj, 'blabla') // 因為blabla不存在,所以此操作無任何影響
    
    function addClass(objNmae, e) {
        //查看元素是否存在,不存在在添加
        if (objNmae.className.split(' ').indexOf(e) == -1) {
            objNmae.className += ' ' + e;
            console.log(objNmae.className);
        }
    
    }
    
    function removeClass(objNmae,e){
        var a = objNmae.className.split(' ');
        if (a.indexOf(e) > -1) {
    
            a.splice(a.indexOf(e),1);
        }
        obj.className = a.join(' ');
        console.log(obj.className);
    }
    
   
6. 寫一個camelize函數,把my-short-string形式的字符串轉化成myShortString形式的字符串,如 (***)

    ```
    camelize("background-color") == 'backgroundColor'
    camelize("list-style-image") == 'listStyleImage'
    ```
    
    ```
        camelize("background-color") == 'backgroundColor';
        camelize("list-style-image") == 'listStyleImage';
    //已修改
            function camelize(str) {
        var num = str.split('-');
        for (var i = 1; i < num.length; i++) {
            num[i] = num[i].charAt(0).toUpperCase() + num[i].substr(1);
        }
        return num.join('');
    }
    ```
7. 如下代碼輸出什么?為什么? (***)

    ```
    arr = ["a", "b"];
    arr.push( function() { alert(console.log('hello hunger valley')) } );
    arr[arr.length-1]()  // ?
    ```
    輸出:彈框alert顯示undefined,控制臺輸出hello hunger valley。
    原因:`arr.push( function() { alert(console.log('hello hunger valley')) } );`這句代碼就是把這個函數添加到數組 arr 的最后一位,該下標是 arr.length-1,`arr[arr.length-1]();`后面有個()所以會調用這個函數,alert里包括console.log('hello hunger valley')所以先執行console.log('hello hunger valley')控制臺輸出hello hunger valley,然后彈出彈框,因為console.log('hello hunger valley')執行完成后會返回undefined,所以彈框顯示的是undefined。

8. 寫一個函數isPalindrome,判斷一個字符串是不是回文字符串(正讀和反讀一樣,比如 abcdcba 是回文字符串, abcdefg不是)

    ```
        function isPalindrome(str){
            for(var i = 0; i<str.length;i++){
    
                if (str.charAt(i) === str.charAt(str.length-i-1)) {
                    return 'yes';
                }else{
                    return 'no';
                }
    
            }
        }
    ```
    ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-9795ce2b88847b39.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

9. 寫一個ageSort函數實現數組中對象按age從小到大排序 (***)

    ```
    var john = { name: "John Smith", age: 23 }
    var mary = { name: "Mary Key", age: 18 }
    var bob = { name: "Bob-small", age: 6 }
    var people = [ john, mary, bob ]
    ageSort(people) // [ bob, mary, john ]
    ```
    ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-d4edc21a2e2b21d2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

10. 寫一個filter(arr, func) 函數用于過濾數組,接受兩個參數,第一個是要處理的數組,第二個參數是回調函數(回調函數遍歷接受每一個數組元素,當函數返回true時保留該元素,否則刪除該元素)。實現如下功能: (****)

    ```
    function isNumeric (el){
        return typeof el === 'number'; 
    }
    arr = ["a",3,4,true, -1, 2, "b"]
    
    arr = filter(arr, isNumeric) ; // arr = [3,4,-1, 2],  過濾出數字
    arr = filter(arr, function(val) { return  typeof val === "number" && val > 0 });  // arr = [3,4,2] 過濾出大于0的整數
    ```
    
    ```
    function filter(arr,fun){
        for(var i = 0;i<arr.length;i++){
            if (!fun(arr[i])) {
                arr.splice(i,1);
            }
        }
    }
    
    function isNumeric (el){
        return typeof el === 'number'; 
    }
    arr = ["a",3,4,true, -1, 2, "b"]
    
    arr = filter(arr, isNumeric) ; // arr = [3,4,-1, 2],  過濾出數字
    arr = filter(arr, function(val) { return  typeof val === "number" && val > 0 });  // arr = [3,4,2] 過濾出大于0的整數
    ```
  ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-4aacda9fe12264c5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)



##字符串
1. 寫一個 ucFirst函數,返回第一個字母為大寫的字符 (***)

    ```
    ucFirst("hunger") == "Hunger"
    ```
    ```
    function ucFirst(str){
            return str[0].toUpperCase()+str.substr(1);
        }
    ```
    ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-b4d2e58e75a03893.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

  ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-dde455a3c06e5f05.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

2. 寫一個函數truncate(str, maxlength), 如果str的長度大于maxlength,會把str截斷到maxlength長,并加上...,如 (****)

    ```
    truncate("hello, this is hunger valley,", 10) == "hello, thi...";
    truncate("hello world", 20) == "hello world"
    ```
    
    ```
    function truncate(str,maxlength){
        if (str.length>maxlength) {
            return str.substr(0,maxlength)+"...";
        }else{
            return str;
        }
    }
    truncate("hello, this is hunger valley,", 10) == "hello, thi...";
    truncate("hello world", 20) == "hello world"
    ```
    ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-6dd95581609f4ca6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


##數字函數
1. 寫一個函數,獲取從min到max之間的隨機整數,包括min不包括max (***)
    
    ```
    function ran(min,max){
        return min+Math.floor(Math.random()*(max-min));
    }
    ```
   ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-a226e85edf0a4ac6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

2. 寫一個函數,獲取從min都max之間的隨機整數,包括min包括max (***)

    ```
    function ran(min,max){
            return min+Math.floor(Math.random()*(max-min+1));
        } 
    
        for (var i = 0; i<20; i++) {
            console.log(ran(15,20));
        }
    ```
    ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-6ce2c749591189b6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

3. 寫一個函數,獲取一個隨機數組,數組中元素為長度為len,最小值為min,最大值為max(包括)的隨機整數 (***)

    ```
    function ran(len,min,max){
    
        var arr = [];
        for(var i =0;i<len;i++){
            var vl=min + Math.floor(Math.random() * (max - min + 1));
            arr.push(vl);
        }
        return arr;
    }
    ```
  ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-d0ce81ff9a83a16a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

4. 寫一個函數,生成一個長度為 n 的隨機字符串,字符串字符的取值范圍包括0到9,a到 z,A到Z。

    ```
    function getRandStr(len){
      //todo...
    }
    var str = getRandStr(10); // 0a3iJiRZap
    ```
    
    ```
    function getRandStr(len){
      //todo...
      var str = '';
      var vl='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      for (var i = 0; i < len; i++) {
        var  num = Math.floor(Math.random()*vl.length);
        str=str+vl[num]
      }
      return str;
      
    }
    var str = getRandStr(10); // 0a3iJiRZap
    console.log(str);
    ```
    ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2858982-19fda7d74c803879.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容