饥人谷技术博客

任务18-数组、字符串、数学函数

2017-01-02  本文已影响0人  饥人谷_桶饭

问答题

代码题

数组

  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](https://img.haomeiwen.com/i2858982/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](https://img.haomeiwen.com/i2858982/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](https://img.haomeiwen.com/i2858982/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](https://img.haomeiwen.com/i2858982/b4d2e58e75a03893.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

  ![Paste_Image.png](https://img.haomeiwen.com/i2858982/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](https://img.haomeiwen.com/i2858982/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](https://img.haomeiwen.com/i2858982/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](https://img.haomeiwen.com/i2858982/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](https://img.haomeiwen.com/i2858982/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](https://img.haomeiwen.com/i2858982/19fda7d74c803879.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
上一篇 下一篇

猜你喜欢

热点阅读