三个实用的javascript小技巧

从后向前获取数组元素

若是你想从后向前获取一个数组的元素,能够这样写:数组

var newArray = [1, 2, 3, 4]

console.log(newArray.slice(-1)) // [4]
console.log(newArray.slice(-2)) // [3, 4]
console.log(newArray.slice(-3)) // [2, 3, 4]
console.log(newArray.slice(-4)) // [1, 2, 3, 4]

短路条件句

若是你想在某个条件逻辑值为true时,执行某个函数,就像这样:函数

if (condition) {
  dosomething()
}

这时,你能够这样子运用短路:spa

condition && dosomething()

用操做符 “||” 来设置默认值

若是你必须给一个变量赋默认值,能够简单的这样写:code

var a

console.log(a) // undefined

a = a || 'default value'

console.log(a) // default value

a = a || 'new value'

console.log(a) // default value
相关文章
相关标签/搜索