美文网首页
有趣的js题目

有趣的js题目

作者: 扶搏森 | 来源:发表于2018-06-13 01:33 被阅读0次

中二分法

从已经排好顺序的数组中取出一个数的位置(也可能是插入一个数到排列好的数组中而不打乱顺序)

function findNum(arr,num){
    let len=arr.length
    let startIndex=0,   //开始位置
    endIndex= len-1     //结束位置
    let centerIndex
    while(true){
        centerIndex=Math.ceil((endIndex-startIndex)/2)  //中间的位置
        if(arr[centerIndex]===num||endIndex<=startIndex){
            return centerIndex
        }
        if(arr[centerIndex]<num){
            startIndex=centerIndex+1
        }else{
            endIndex=centerIndex-1
        }
    }
}
const arr=[2,3,5,6,7,9]
findNum(arr,3)

最大公约数

10和15的的公约数为+-1,+-5,所以最大公约数是5

function getCommonDivisor(a,b){
    let temp
    const min=Math.min(a,b)
    for(let i=1;i<min;i++){
        if(a%i===0&&b%i===0){
            temp=i
        }
    }
    return temp
}
getCommonDivisor(10,15)

原型链继承问题

function Parent(){
    this.a=1
    this.b=[2,3,this.a]
    this.c={demo:4}
    this.show=function(){
        console.log(this.a,this.b,this.c)
    }
}
function Child(){
    this.change=function(){
        this.b.push(this.a)
        this.c.demo=this.a++
    }
}
Child.prototype=new Parent()
var parent=new Parent()
var child1=new Child()
var child2=new Child()
child1.a=11
child2.a=22
parent.show()
child1.show()
child2.show()
child1.change()
child2.change()
parent.show()
child1.show()
child2.show()
结果展示

通过 new Parent()继承会导致child变了也会改变同样new出来的兄弟,因为2的原型链都是指向同一个按引用传递的一个对象。

函数柯粒化

问题:写一个mul函数调用时将生成以下输出:

console.log(mul(2)(3)(4)); // output : 24

console.log(mul(4)(3)(4)); // output : 48

下面的是知乎给出的答案:知乎答案

function mul(x) {
    const result = (y) => mul(x * y); 
    result.valueOf = () => x;
    return result;
}

console.log(mul(3))
-> 3
console.log(mul(3)(2))
-> 6
console.log(mul(3)(2)(4))
-> 24
console.log(mul(3)(2)(4)(5))
-> 120

好吧,很强。当时做这个题的时候应该想到了传不同参数的时候会返回不同的结果

mul(3) 返回 3或者3*,这个时候需要进行不同处理了,return result,读值的时候走了valueOf,返回自身

merge extend assign 区别

别人讲的特别仔细

链接地址

相关文章

  • 有趣的js题目

    中二分法 从已经排好顺序的数组中取出一个数的位置(也可能是插入一个数到排列好的数组中而不打乱顺序) 最大公约数 1...

  • 有趣的题目

    1. 与概率有关的故事 国王决定给一个判了死刑的犯人免死的机会,国王令血犯人将50个白球个50个黑球放进2完全相同...

  • JS题目

    JS 1、原型/原型链/构造函数/实例/继承 1. proto(原型) 每个对象又有proto属性,指向创建他的构...

  • js的部分题目

  • js经典题目

    1闭包 链接:学习Javascript闭包(Closure) setTimeout在js单线程中只是放在队列中并未...

  • js题目练习

    7.23 1,计算给定数组arr中所有元素的总和,数组中的元素均为Number 类型。例如:[1,2,3,4]--...

  • js数组题目

    1、寻找两个数组中相同的元素中最小的元素 2、判断一个字符串中出现次数最多的字符,统计这个次数var str=’a...

  • js数组题目

    js面试题 js数组 一、按要求分割数组 将"js,数组,分类"字符串数组以/分割 for循环累加 join()把...

  • Js常见题目2

    移动端是怎么做适配的? 1.使用 标签包含 name、 content...

  • Js常见题目3

    3.用过CSS3吗? 实现圆角矩形和阴影怎么做? 圆角border-radius; http://js.jiren...

网友评论

      本文标题:有趣的js题目

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