javascript面试题

  • 尝试给一组数字排序

    JavaScript的sort()函数在默认情况下使用字母数字(字符串Unicode码点)排序。

    所以[1, 2, 5, 10].sort()会输出[1, 10, 2, 5]。

    要正确的排序一个数组,你可以用[1, 2, 5, 10].sort((a, b) => a - b)

  • new Date()

    new Date()可以接受:

    * 没有参数: 返回当前时间
    * 一个参数x: 返回1970年1月1日 + x毫秒
    * new Date(1, 1, 1)返回1901,二月,1号。因为,第一个参数表示1900年加1年,第二个参数表示这一年的第二个月,第三个参数表示这个月的第一天。
    * new Date(2016, 1, 1)不会给1900年加上2016。它仅代表2016年。

  • Replace并不是“替代”

    let s = 'bob';
    const replaced = s.replace('b', 'l');
    replaced === 'lob';
    s === 'bob'

    replace 不改变原先变量的值,replace只会替换第一个匹配的字符串:

    如果想替换所有匹配的字符串,可以使用带/g标志的正则表达式:

    'bob'.replace(/b/g, 'l') === 'lol'  //替换所有匹配的字符串

     

  • 比较的时候注意

    'abc' === 'abc'  //true
    
    1 === 1  //true
    
    [1, 2, 3] === [1, 2, 3]  //false
    
    {a: 1} === {a: 1}  //false
    
    {} === {}

    原因: [1, 2, 3]和[1, 2, 3]是两个独立的数组。它们只是恰巧包含相同的值。它们具有不同的引用,无法同 === 相比较。

  • 数组不是原始数据类型

    const Greeters = [];
    
    for (var i = 0; i< 10; i++) {
      Greeters.push(function() {
        return console.log(i)  
       })      
    }
    
    Greeters[0]()  //10
    
    Greeters[1]()  //10
    
    Greeters[2]()  //10

    因为console.log出的是运行完所有结果的结果,如果让他输出0,1,2...

    用let替代var

    let和var的不同在于作用域。var的作用域是最近的函数块,let的作用域是最近的封闭块,封闭块可以小于函数块(如果不在任何块中,则let和var都是全局的)。

    用bind

    Greeters.push(console.log.bind(null, i));

     

  • bind

    class Foo {
      constructor (name) {
        this.name = name
      }
      greet () {
        console.log('hello, this is ', this.name)
      }
      someThingAsync () {
        return Promise.resolve()
      }
      asyncGreet () {
        this.someThingAsync()
        .then(this.greet)
      }
    }
    
    new Foo('dog').asyncGreet()

    结果:  Cannot read property 'name' of undefined

    原因: greet没有在正确的上下文中运行。同样依然有很多解决方案。

    asyncGreet() {
      this.somethingAsync()
        .then(this.greet.bind(this))    
    }


    这样可以确保类的实例作为上下文调用greet

    如果不让greet在实例上下文运行,可以在constructor中绑定它:


    class Foo {
      constructor(name) {
        this.name = name
        this.greet = this.greet.bind(this)  
      }  
    }


    还可以用箭头函数保留上下文


    asyncGreet() {
      this.someThingAsync() 
        .then(() => {
            this.greet()
        })  
    }

     

posted @ 2017-06-22 17:12  ontheway1215  阅读(142)  评论(0编辑  收藏  举报