OSDN Git Service

Regular updates
[twpd/master.git] / js-lazy.md
1 ---
2 title: JavaScript lazy shortcuts
3 category: JavaScript
4 layout: 2017/sheet
5 ---
6
7 ## Shortcuts
8 {: .-left-reference}
9
10 ### Examples
11
12 ```js
13 n = +'4096'    // n === 4096
14 s = '' + 200   // s === '200'
15 ```
16
17 ```js
18 now = +new Date()
19 isPublished = !!post.publishedAt
20 ```
21
22 ### Shortcuts
23
24 | What | Lazy mode | "The right way" |
25 | --- | --- | --- |
26 | String to number | `+str` | `parseInt(str, 10)` _or_ `parseFloat()` |
27 | Math floor | `num | 0` | `Math.floor(num)` |
28 | Number to string | `'' + num` | `num.toString()` |
29 | Date to UNIX timestamp | `+new Date()` | `new Date().getTime()` |
30 | Any to boolean | `!!value` | `Boolean(value)` |
31 | Check array contents | `if (~arr.indexOf(v))` | `if (arr.includes(v))` |
32 {: .-left-align.-headers}
33
34 `.includes` is ES6-only, otherwise use `.indexOf(val) !== -1` if you don't polyfill.