任务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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,829评论 1 331
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,603评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,846评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,600评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,780评论 3 272
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,695评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,136评论 2 293
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,862评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,453评论 0 229
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,942评论 2 233
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,347评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,790评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,293评论 3 221
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,839评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,448评论 0 181
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,564评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,623评论 2 249

推荐阅读更多精彩内容