美文网首页
网易微专业之《前端工程师》学习笔记(14)-JS期末测试主观题

网易微专业之《前端工程师》学习笔记(14)-JS期末测试主观题

作者: 荷小音 | 来源:发表于2016-01-31 22:21 被阅读2502次

一、(8分)
函数myType用于根据输入参数返回相应的类型信息。
语法如下:

 var str = myType (param);

使用范例如下:

 myType (1); 返回值: "number"
 myType (false); 返回值: "boolean"
 myType ({}); 返回值: "object"
 myType ([]); 返回值:" Array"
 myType (function(){}); 返回值:"function"
 myType (new Date()); 返回值: "Date"

请写出函数myType的实现代码。

解:

function myType(param){
    if(typeof param=="object"){

if((Object.prototype.toString.call(param).slice(8,-1))=="Object"){return "object"}else{return Object.prototype.toString.call(param).slice(8,-1);}

    }else{return typeof param;}


}

//打印测试如下:
myType (1);
 //"number"
myType (false);
//"boolean"
myType ({});
//"object"
myType ([]); 
//"Array"
myType (function(){});
//"function"
myType (new Date());
//"Date"

二、(10分)
函数search用于在一个已排序的数字数组中查找指定数字。
语法如下:

 var index = search(arr, dst);

使用范例如下:

 var arr = [1, 2, 4, 6, 7, 9, 19,20, 30, 40, 45, 47];
 search(arr, 45); 返回值: 10

请写出函数search的实现代码 请给出函数,要求不能使用Array的原型方法,且算法时间复杂度低于O(n)。

解:

function search(arr,dst){
    var l,r;
        l = 0;
        r=arr.length-1;
    while(l <= r){
                    var m = Math.floor((l+r)/2);
                    if(dst<arr[m]){r=m-1;}
                    else if(arr[m]<dst){l=m+1;}
                    else{
                       if(arr[m-1]==dst){return m-1;}//添加一个判断
                       return m;
                        }
                        }  
    return -1;
}

var arr= [1, 2, 4, 6, 7, 9, 19,20, 30, 40, 45, 47];
search(arr, 45);//10

var arr1= [1,2,3,4,4,5];
search(arr, 4);//3

三、(12分)
函数formatDate用于将日期对象转换成指定格式的字符串,语法如下:
var str = formatDate(date, pattern);
其中pattern的全格式为"yyyy-MM-dd HH:mm:ss"
使用范例如下:
var date = new Date(2001, 8, 11, 8, 26, 8);
formatDate(date, "yyyy"); 返回值: "2001"
formatDate(date, "yyyy-MM-dd"); 返回值: "2001-09-11"
formatDate(date, "yyyy-MM-dd HH"); 返回值: "2001-09-11 08"
formatDate(date, "yyyy-MM-dd HH:mm:ss"); 返回值: "2001-09-11 08:26:08"
请写出函数formatDate的实现代码。

解:

function formatDate (date,pattern) {
var fuck = pattern;
  fuck=fuck.replace(/yyyy/,date.getFullYear());
  fuck=fuck.replace(/MM/,date.getMonth());
  fuck=fuck.replace(/dd/,date.getDate());
  fuck=fuck.replace(/HH/,date.getHours());
  fuck=fuck.replace(/mm/,date.getMinutes());
  fuck=fuck.replace(/ss/,date.getSeconds());
  return fuck;
}
var date = new Date(2001,8,11,8,26,8);
formatDate(date,"2001")

相关文章

网友评论

      本文标题:网易微专业之《前端工程师》学习笔记(14)-JS期末测试主观题

      本文链接:https://www.haomeiwen.com/subject/wgkskttx.html