JavaScript坑

1.尝试给一组数字排序

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

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

正解:[1,2,5,10].sort((a,b)=>a-b)
        这个函数是升序排序,如果想逆序排序改成return b-a;就行了.
          --->该颜色选中区是 function sortNumber(a,b) {return a-b;}
 
其实这个函数相当于一个委托(或许说谓词函数更为贴切一些),因为要对数组排序,必然要涉及到两个数组成员的比较,这个函数为你提供一种选择,以改变默认的大小比较规则,
排序结果根据这个规则进行比较(函数返回值小于0认为是第一个元素小于第二个元素,等于0是两个元素相等,大于0是第一个元素大于第二个元素)。
因为sort()函数使用的是冒泡排序,冒泡排序会重复地走访要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来,一直重复地进行直到说该数列已经排序完成。
如果((a,b)=>a-b)>0(即正数)就把a和b的位置交换,也就是较小的一个数会排到前面;

2.new Date()

  1. 没有参数:返回当前时间。
  2. 一个参数 X:返回1970年1月1日+X毫秒。
  3. new Date(1,1,1) :返回1900年+1,一月+1,,第一天+1。也就是1902年2月1日。
  4. new Date(2016,1,1):2016年2月1 号

3.Replace并不是“替代”

let s = "bob"

const replaced = s.replace('b','l')

replaced ==="lob"

s ==="bob"

replace只会替换第一个匹配的字符串。

如果想替换所有匹配的字符串,可以使用/g

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

4.比较的时候要注意

//these are ok

’abc'  ===  'abc'  //true

1 === 1  //true

//these are not

[1,2,3] === [1,2,3]  //false

{a:1} === {a:1} //false

{} === {}  //false

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

5.数组不是原始数据类型

typeof {} ==='object' //true

typeof 'a' === 'string'  //true

typeof 1 ===number  //true

//but

typeof [] ==='object'   /true

如果想知道变量是不是数组,仍然可以用Array.isArray(myVar)

6.闭包

这是个很有名的面试题:

const Gteeters = []

for(var i=0;i<10;i++){

   Gteeters.push(function(){

    return console.log(i)

  })

}

Gteeters[0]() //10

Gteeters[1]() //10

Gteeters[2]() //10

输出结果并不是0,1,2...

这里有两种可能解决的方案:

1.用let替代 var. Boom. 解决了.

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

2.替代方法:用bind:

Gteeters.push(console.log.bind(null.i))

7.bind

你认为会输出什么?

calss 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中绑定它:

calss Foo{

  constructor(name){

    this.name = name

    this.greet = this.greet.bind(this)

  }

}

你还应该知道箭头函数(=>)可以用来保留上下文。这个方法也可以:

asyncGreet(){

  this.someThingAsync()

  .then(() = > {

    this.greet()

  })

}

 
 
 
原文地址:https://www.cnblogs.com/maoyizhimi/p/7054467.html