Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

三个实用的javascript小技巧 #60

Open
susouth opened this issue Dec 9, 2019 · 0 comments
Open

三个实用的javascript小技巧 #60

susouth opened this issue Dec 9, 2019 · 0 comments
Labels
JavaScript 跟js相关的面试题 No.60

Comments

@susouth
Copy link
Contributor

susouth commented Dec 9, 2019

📚在线阅读:三个实用的javascript小技巧 - No.60

从后向前获取数组元素

如果你想从后向前获取一个数组的元素,可以这样写:

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()
}

这时,你可以这样子运用短路:

condition && dosomething()

用操作符 "||" 来设置默认值

如果你必须给一个变量赋默认值,可以简单的这样写:

var a

console.log(a) // undefined

a = a || 'default value'

console.log(a) // default value

a = a || 'new value'

console.log(a) // default value

扩展阅读:

@susouth susouth added JavaScript 跟js相关的面试题 No.60 labels Dec 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 跟js相关的面试题 No.60
Projects
None yet
Development

No branches or pull requests

1 participant