代码总结-1

95 阅读2分钟

1、解构赋值之报错。

let [x = y, y = 1] = []
// Uncaught ReferenceError: y is not defined at <anonymous>:1:10

报错原因是:x用到默认值y时,y还没有被声明。

2、关于括号。

  let obj = {}
  let arr = [];

  ({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true})

当 let arr = [];省略分号时会报错,下面的括号会上移。

3、将字符串反转。

let a = "abcdefg"
a = a.split("").reverse().join("")

先使用split将字符串变为数组,使用reverse反转数组,join将数组变回字符串,得到字符串反转。

4、判断绝对相等。

 -0 === 0 // true
Object.is(0,-0) // false

Object.is效率并不高,主要用于处理特殊的相等比较。

5、 关于函数参数。

function foo(x){
    x.push(4)
    x;

    x = [4,5,6]
    x.push(7)
    x
}
let a = [1,2,3]
foo(a)
a

向函数传递a时,实际上是将a的一个复本赋值给x,而a仍旧指向[1,2,3],在函数中可以通过x来更改数组的值,但x=[4,5,6]并不影响a的指向。

可通过下面方法实现:

function foo(x){
    x.push(4)
    x;

    x.length = 0
    x.push(4,5,6,7)
    x
}

let a = [1,2,3]
foo(a)
a

6、间接访问对象的内部属性[[Class]]访问对象的分类,如Array和Function等。

Object.prototype.toString.call([1,2,3,4,5])
// '[object Array]'
Object.prototype.toString.call(/regex-literal/i)
// '[object RegExp]'
Object.prototype.toString.call(function fn(x){console.log(x)})
// '[object Function]'
Object.prototype.toString.call(null)
// '[object Null]'
Object.prototype.toString.call(undefined)
// '[object Undefined]'
Object.prototype.toString.call("abcd")
// '[object String]'
Object.prototype.toString.call( 42 )
// '[object Number]'
Object.prototype.toString.call( false )
// '[object Boolean]'

对于对象的子类内部的[[Class]]属性和创建该对象的内建原生函数相对应。

对于null和undefined虽然原生构造函数不存在,但内部[Class]属性值仍旧为'Null'和'Undefined'。

对于数字、字符串和布尔,其值被各自的封装对象自动包装,之后再取[[Class]]属性。

7、创建包含undefined的单元而非稀疏数组。

let a = Array.apply(null,{length:3})

实践中永远不要创建和使用空单元数组(稀疏数组),想创建undefined单元的数组可按照上述方法。

8、indexOf的使用方法。

let a = "hello world"

if(a.indexOf("lo") >= 0){ // true
    // 找到匹配
}

if(a.indexOf("lo") !== -1){ // true
    // 找到匹配
}
if(a.indexOf("ol") < 0){ // true
    // 没有找到匹配
}
if(a.indexOf("ol") === -1){ // true
    // 没有找到匹配
}

9、indexOf()配合~和!。

在字符串中搜索指定的字符串,如果找到就返回子字符串所在的位置(从0开始),否则返回-1。还可以使用~配合操作。

let a = "hello world"
a.indexOf("lo") // 3
~a.indexOf("lo") // -4

if(~a.indexOf("lo")){ // true
    // 找到匹配
}

~a.indexOf("ol")  // 0 falsy值 假值
!~a.indexOf("ol") // true
if(!~a.indexOf("ol")){ // true
    // 没有找到匹配
}

10、关于||的使用,设定默认值。

function foo(a,b){
    a = a|| "hello"
    b = b|| "world"

    console.log(a+ " "+b)
}

foo()
foo("hi","xinhai")