码迷,mamicode.com
首页 > Web开发 > 详细

JS微专业作业答案

时间:2016-05-20 17:28:47      阅读:458      评论:0      收藏:0      [点我收藏+]

标签:

 

function type(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}

 

 

实现type函数用于识别标准类型和内置对象类型,语法如下:

var t = type(obj);

使用举例如下:

 

  1. var t = type(1) // t==="number"
  2. var t = type(new Number(1)) // t==="number"
  3. var t = type("abc"// t==="string"
  4. var t = type(new String("abc")) // t==="string"
  5. var t = type(true// t==="boolean"
  6. var t = type(undefined) // t==="undefined"
  7. var t = type(null// t==="null"
  8. var t = type({}) // t==="object"
  9. var t = type([]) // t==="array"
  10. var t = type(new Date) // t==="date"
  11. var t = type(/\d/) // t==="regexp"
  12. var t = type(function(){}) // t==="function"

 

 

ES5中定义的Object.create(proto)方法,会创建并返回一个新的对象,这个新的对象以传入的proto对象为原型。

语法如下:

    Object.create(proto)  (注:第二个参数忽略)

        proto —— 作为新创建对象的原型对象

使用示例如下:

    var a = Object.create({x: 1, y: 2});

    Object.create = Object.create || function(obj) {

    var F = function() {};
    F.prototype = obj;
    return new F();
}

 

Object.create在某些浏览器没有支持,请给出Object.create的兼容实现。

 

Function.prototype.bind = function(obj) {
    var aa = this,
        args = arguments;
    return function() {
        aa.apply(obj, Array.prototype.slice.call(args, 1))
    }
}

 

function fibonacci(n) {
    if (n == 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    } else {
        return (arguments.callee(n - 1) + arguments.callee(n - 2));
    }
}

 

function search(arr,dst){
    var type = Object.prototype.toString.call(arr).slice(8,-1);
    if(type != ‘Array‘){
        throw TypeError(‘Object prototype may only be an Array‘)
    }
    var len = arr.length;
    if( !len){
        return -1;
    }
 
    var l = 0;
    var h = len - 1;
    while(l <= h){
        var m = Math.floor( (h+l)/2 );
        if( arr[m] == dst ){
            return m;
        }else if( dst < arr[m] ){ //左半部分
            h = m - 1;
        }else{ //右半部分
            l = m + 1;
        }
 
    }
}
var arr = [1,2,4,6,7,9,19,20,30,40,45,47];
alert( search(arr,45) )

 

JS微专业作业答案

标签:

原文地址:http://www.cnblogs.com/sakurashadow/p/5512694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!