diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6b0d5fb6..58f380b6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,18 +1,28 @@ # How to submit your tip -To submit a tip to the list, fork the repository and add your tip to a new file in the correct folder (according language). The name of the file should be `2016-xx-xx-name-of-your-tip`. +To submit a tip to the list, fork the repository and add your tip in a new file in the correct folder (according language). The name of the file should be `2016-xx-xx-name-of-your-tip`. -Use [this format](https://github.com/loverajoel/jstips/blob/gh-pages/POST_TEMPLATE.md) when writing your tip. Your tip should be readable in less than two minutes. You may add links to other sites or videos that give more insight if you wish. +Use [this format](https://github.com/loverajoel/jstips/blob/gh-pages/POST_TEMPLATE.md) when writing your tip. -Once your tip is ready, [issue a pull request](https://help.github.com/articles/using-pull-requests/) with this [PR template](https://github.com/loverajoel/jstips/blob/gh-pages/PULL_REQUEST_TEMPLATE.md) and your tip will be reviewed. Every day one tip will be merged from the available pull requests. +### Requirements +- The tip should be readable in less than two minutes +- Adding links to other sites or videos that give more insight is welcome +- Mark JS code with ```js +- Don't mention "JavaScript" in the title (as our tips are about it anyway) +- Use backticks (`) to mark code in the title ‐ _Warning_: Titles must not start with backticks! + +Once your tip is ready, [issue a pull request](https://help.github.com/articles/using-pull-requests/) with this [PR template](https://github.com/loverajoel/jstips/blob/gh-pages/PULL_REQUEST_TEMPLATE.md) and your tip will be reviewed (see below). # Notes -Leave the date and the tip number with **xx**. When we decide to merge the pull request, you will add them and squash your commits. +Leave the date and the tip number as **xx**. When the PR is `ready to merge`, we will tell you the correct numbers. Please also [squash](https://davidwalsh.name/squash-commits-git) your commits. # Tip flow -**Tip sent** -> **Tip in review** -> **Tip Approved** +**Tip proposal** ⇒ **Tip under review** ⇒ **Tip ready to merge** + +- When you send a tip, it has to pass the review process and while that happens, its status is `under review`. +- After the tip had been reviewed by 5 people and they have given their ship it emote (:shipit:), the tip is `ready to merge`. + -- When you send a tip, it now has to pass the review process and while that happens, it status will be `under-review`. -- After the tip is reviewed by 5 people and they gave their :shipit:, then the tip will be `ready to merge` +We are looking forward to your contribution! diff --git a/CONTRIBUTING_zh_TW.md b/CONTRIBUTING_zh_TW.md index ed8a04de..55a3fd5c 100644 --- a/CONTRIBUTING_zh_TW.md +++ b/CONTRIBUTING_zh_TW.md @@ -4,7 +4,7 @@ 當你撰寫你的 tip 時,請使用[這個格式](https://github.com/loverajoel/jstips/blob/gh-pages/POST_TEMPLATE.md)。你的 tip 應該要可以在兩分鐘內讀懂。你可以連結到其他的網站或者是影片讓我們了解更多。 -當你的 tip 準備好了,依據這個 [PR 樣板](https://github.com/loverajoel/jstips/blob/gh-pages/PULL_REQUEST_TEMPLATE.md),[發送一個 PR](https://help.github.com/articles/using-pull-requests/)你的 tip 將會被校閱。每天都會有 tip 從可用的 PR 中被合併(merged)。 +當你的 tip 準備好了,依據這個 [PR 樣板](https://github.com/loverajoel/jstips/blob/gh-pages/PULL_REQUEST_TEMPLATE.md),[發送一個 PR](https://help.github.com/articles/using-pull-requests/) 你的 tip 將會被校閱。每天都會有 tip 從可用的 PR 中被合併(merged)。 # 注意 diff --git a/POST_TEMPLATE.md b/POST_TEMPLATE.md index b6ddc168..a0841408 100644 --- a/POST_TEMPLATE.md +++ b/POST_TEMPLATE.md @@ -2,7 +2,7 @@ layout: *post title: Demo post -tip-number: 01 +tip-number: xx tip-username: tip_js tip-username-profile: https://twitter.com/tips_js tip-tldr: Just a demo diff --git a/_config.yml b/_config.yml index a7e8f304..a1dac583 100644 --- a/_config.yml +++ b/_config.yml @@ -63,10 +63,10 @@ baseurl: "" # !! You don't need to change any of the configuration flags below !! # -markdown: redcarpet -highlighter: pygments permalink: /:categories/:title/ +markdown: kramdown +highlighter: rouge paginate: 10 paginate_path: "/:num/" @@ -142,16 +142,16 @@ transl: menu: home: txt: 首頁 - link: / + link: /zh_TW about: txt: 關於 link: /zh_TW/about subscribe: txt: 訂閱 submit_your_tip: - txt: 提交你的小知識 + txt: 提交你的 tip link: https://github.com/loverajoel/jstips/blob/gh-pages/CONTRIBUTING_zh_TW.md - footer_subscribe_message: 訂閱更多更棒的每日小知識! + footer_subscribe_message: 訂閱更多更棒的每日 tips! footer_placeholder_subscribe: your@email.com - arrow_prev: 上一篇小知識 - arrow_next: 下一篇小知識 + arrow_prev: 上一篇 tip + arrow_next: 下一篇 tip diff --git a/_posts/en/2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md b/_posts/en/2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md index ee3bd8c9..9bc10d47 100644 --- a/_posts/en/2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md +++ b/_posts/en/2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md @@ -17,14 +17,14 @@ You just have to concat everything into an array first. `Array.concat` will acce ```javascript function printUpperCase(words) { - var elements = [].concat(words); + var elements = [].concat(words || []); for (var i = 0; i < elements.length; i++) { console.log(elements[i].toUpperCase()); } } ``` -`printUpperCase` is now ready to accept a single node or an array of nodes as its parameter. +`printUpperCase` is now ready to accept a single node or an array of nodes as its parameter. It also avoids the potential `TypeError` that would be thrown if no parameter was passed. ```javascript printUpperCase("cactus"); diff --git a/_posts/en/2016-01-18-rounding-the-fast-way.md b/_posts/en/2016-01-18-rounding-the-fast-way.md index ca07e0de..046e7c3c 100644 --- a/_posts/en/2016-01-18-rounding-the-fast-way.md +++ b/_posts/en/2016-01-18-rounding-the-fast-way.md @@ -1,37 +1,105 @@ --- layout: post -title: Rounding the fast way +title: Truncating the fast (but risky) way tip-number: 18 tip-username: pklinger tip-username-profile: https://github.com/pklinger -tip-tldr: Today's tip is about performance. Ever came across the double tilde `~~` operator? It is sometimes also called the double NOT bitwise operator. You can use it as a faster substitute for `Math.floor()`. Why is that? +tip-tldr: `~~X` is usually a faster `Math.trunc(X)`, but can also make your code do nasty things. categories: - en --- -Today's tip is about performance. [Ever came across the double tilde] (http://stackoverflow.com/questions/5971645/what-is-the-double-tilde-operator-in-javascript) `~~` operator? It is sometimes also called the double NOT bitwise operator. You can use it as a faster substitute for `Math.floor()`. Why is that? +This tip is about performance...with a hidden price tag. -One bitwise shift `~` transforms the 32 bit converted input into `-(input+1)`. The double bitwise shift therefore transforms the input into `-(-(input + 1)+1)` making it a great tool to round towards 0. For numeric input, it therefore mimics the `Math.ceil()` for negative and `Math.floor()` for positive input. On failure, `0` is returned, which might come in handy sometimes instead of `Math.floor()`, which returns a value of `NaN` on failure. +Have you ever come across the [double tilde `~~` operator](http://stackoverflow.com/questions/5971645/what-is-the-double-tilde-operator-in-javascript)? It's also often called the "double bitwise NOT" operator. You can often use it as a faster substitute for `Math.trunc()`. Why is that? -```javascript +One bitwise shift `~` first truncates `input` to 32 bits, then transforms it into `-(input+1)`. The double bitwise shift therefore transforms the input into `-(-(input + 1)+1)` making it a great tool to round towards zero. For numeric input, it therefore mimics `Math.trunc()`. On failure, `0` is returned, which might come in handy sometimes instead of `Math.trunc()`, which returns `NaN` on failure. + +```js // single ~ console.log(~1337) // -1338 // numeric input console.log(~~47.11) // -> 47 -console.log(~~-12.88) // -> -12 console.log(~~1.9999) // -> 1 console.log(~~3) // -> 3 +``` + +However, while `~~` is probably a better performer, experienced programmers often stick with `Math.trunc()` instead. To understand why, here's a clinical view on this operator. + +### INDICATIONS + +##### When every CPU cycle counts +`~~` is probably faster than `Math.trunc()` across the board, though you should [test that assumption](https://jsperf.com/jsfvsbitnot/10) on whichever platforms matter to you. Also, you'd generally have to perform millions of such operations to have any visible impact at run time. + +##### When code clarity is not a concern +If you're trying to confuse others, or get maximum utility from your minifier/uglifier, this is a relatively cheap way to do it. + +### CONTRAINDICATIONS + +##### When your code needs to be maintained +Code clarity is of great importance in the long term, whether you work in a team, contribute to public code repos, or fly solo. As [the oft-quoted saying](http://c2.com/cgi/wiki?CodeForTheMaintainer) goes: +> Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live. + +For a solo programmer, that psychopath is inevitably "you in six months". + +##### When you forget that `~~` always rounds to zero +Newbie programmers may fixate on the cleverness of `~~`, forgetting the significance of "just drop the fractional portion of this number". This can easily lead to **fencepost errors** (a.k.a. "off-by-one") when transforming floats to array indices or related ordinal values, where a different kind of fractional rounding may actually be called for. (Lack of code clarity usually contributes to this problem.) + +For instance, if you're counting numbers on a "nearest integer" basis, you should use `Math.round()` instead of `~~`, but programmer laziness and the impact of **_10 whole characters saved per use_** on human fingers often triumph over cold logic, leading to incorrect results. -// on failure -console.log(~~[]) // -> 0 +In contrast, the very names of the `Math.xyz()` functions clearly communicate their effect, reducing the probability of accidental errors. + +##### When dealing with large-magnitude numbers +Because `~` first does a 32-bit conversion, `~~` results in bogus values around ±2.15 billion. If you don't properly range-check your input, a user could trigger unexpected behavior when the transformed value ends up being a great distance from the original: +```js +a = 2147483647.123 // maximum positive 32-bit integer, plus a bit more +console.log(~~a) // -> 2147483647 (ok) +a += 10000 // -> 2147493647.123 (ok) +console.log(~~a) // -> -2147483648 (huh?) +``` +One particularly vulnerable area involves dealing with Unix epoch timestamps (measured in seconds from 1 Jan 1970 00:00:00 UTC). A quick way to get such values is: +```js +epoch_int = ~~(+new Date() / 1000) // Date() epochs in milliseconds, so we scale accordingly +``` +However, when dealing with timestamps after 19 Jan 2038 03:14:07 UTC (sometimes called the **Y2038 limit**), this breaks horribly: +```js +// epoch timestamp for 1 Jan 2040 00:00:00.123 UTC +epoch = +new Date('2040-01-01') / 1000 + 0.123 // -> 2208988800.123 + +// back to the future! +epoch_int = ~~epoch // -> -2085978496 +console.log(new Date(epoch_int * 1000)) // -> Wed Nov 25 1903 17:31:44 UTC + +// that was fun, now let's get real +epoch_flr = Math.floor(epoch) // -> 2208988800 +console.log(new Date(epoch_flr * 1000)) // -> Sun Jan 01 2040 00:00:00 UTC +``` + +##### When the original input wasn't sanitized +Because `~~` transforms every non-number into `0`: +```js +console.log(~~[]) // -> 0 console.log(~~NaN) // -> 0 console.log(~~null) // -> 0 - -// greater than 32 bit integer fails -console.log(~~(2147483647 + 1) === (2147483647 + 1)) // -> 0 ``` +some programmers treat it as alternative to proper input validation. However, this can lead to strange logic bugs down the line, since you're no longer distinguishing between invalid inputs and actual `0` values. This is therefore _not_ a recommended practice. + +##### When so many people think `~~X == Math.floor(X)` +Most people who write about "double bitwise NOT" incorrectly equate it with `Math.floor()` for some reason. If you can't write about it accurately, odds are good you'll eventually misuse it. + +Others are more careful to mention `Math.floor()` for positive inputs and `Math.ceil()` for negative ones, but that forces you to stop and think about the values you're dealing with. This defeats the purpose of `~~` as a handy no-gotchas shortcut. + +### DOSAGE +Avoid where possible. Use sparingly otherwise. -Although `~~` may perform better, for the sake of readability please use `Math.floor()`. \ No newline at end of file +### ADMINISTRATION +1. Apply cautiously. +2. Sanitize values before applying. +3. Carefully document relevant assumptions about the values being transformed. +4. Review code to deal with, at minimum: + * logic bugs where invalid inputs are instead passed to other code modules as valid `0` values + * range errors on transformed inputs + * fencepost errors due to incorrect rounding direction diff --git a/_posts/en/2016-01-27-short-circuit-evaluation-in-js.md b/_posts/en/2016-01-27-short-circuit-evaluation-in-js.md index f8da3285..867f7adf 100644 --- a/_posts/en/2016-01-27-short-circuit-evaluation-in-js.md +++ b/_posts/en/2016-01-27-short-circuit-evaluation-in-js.md @@ -51,20 +51,20 @@ The logical OR could also be used to set a default value for function argument. ```js function theSameOldFoo(name){ - name = name || 'Bar' ; - console.log("My best friend's name is " + name); + name = name || 'Bar' ; + console.log("My best friend's name is " + name); } theSameOldFoo(); // My best friend's name is Bar theSameOldFoo('Bhaskar'); // My best friend's name is Bhaskar ``` The logical AND could be used to avoid exceptions when using properties of undefined. -Example:- +Example: ```js var dog = { bark: function(){ - console.log('Woof Woof'); - } + console.log('Woof Woof'); + } }; // Calling dog.bark(); diff --git a/_posts/en/2016-02-15-detect-document-ready-in-pure-js.md b/_posts/en/2016-02-15-detect-document-ready-in-pure-js.md index c6ef3b18..2fb38647 100644 --- a/_posts/en/2016-02-15-detect-document-ready-in-pure-js.md +++ b/_posts/en/2016-02-15-detect-document-ready-in-pure-js.md @@ -19,7 +19,7 @@ if (document.readyState === 'complete') { } ``` -You can detect when the document it's ready... +You can detect when the document is ready... ```js diff --git a/_posts/zh_CN/2016-02-26-extract-unix-timestamp-easily.md b/_posts/zh_CN/2016-02-26-extract-unix-timestamp-easily.md new file mode 100644 index 00000000..8782ff03 --- /dev/null +++ b/_posts/zh_CN/2016-02-26-extract-unix-timestamp-easily.md @@ -0,0 +1,44 @@ +--- +layout: post + +title: 简单获取unix时间戳 +tip-number: 49 +tip-username: nmrony +tip-username-profile: https://github.com/nmrony +tip-tldr: 在Javascript里,你可以简单的取得unix时间戳 + +categories: + - zh_CN +--- + +我们经常需要使用unix时间戳计算。有很多方法可以取得unix时间戳。目前取得unix时间戳最简单最快的方法是: + +```js +const timestamp = Date.now(); +``` +或 + +```js +const timestamp = new Date().getTime(); +``` + +要取得一个具体时间的unix时间戳,将`yyyy-mm-dd`作为参数传递给`Date`构造函数。例如 + +```js +const timestamp = new Date('2012-06-08').getTime() +``` +你还可以像下面一样,在声明`Date`对象的时候添加一个`+`号 + +```js +const timestamp = +new Date() +``` +或者对于具体时间 + +```js +const timestamp = +new Date('2012-06-08') +``` +在底层,运行时调用了`Date`对象的`valueOf`方法。然后一元操作符`+`调用了之前返回值的`toNumber()`方法。想要了解更多内容请参考下面链接 + +* [Date.prototype.valueOf](http://es5.github.io/#x15.9.5.8) +* [Unary + operator](http://es5.github.io/#x11.4.6) +* [toNumber()](http://es5.github.io/#x9.3) diff --git a/_posts/zh_TW/2015-12-29-insert-item-inside-an-array.md b/_posts/zh_TW/2015-12-29-insert-item-inside-an-array.md index 1388088e..b9aba6f3 100644 --- a/_posts/zh_TW/2015-12-29-insert-item-inside-an-array.md +++ b/_posts/zh_TW/2015-12-29-insert-item-inside-an-array.md @@ -5,42 +5,177 @@ title: 在陣列中加入元素 tip-number: 00 tip-username: loverajoel tip-username-profile: https://github.com/loverajoel -tip-tldr: 在一個存在的陣列加入新的元素是一件很常見的事情,你可以使用 push 將元素加入到陣列的末端,或是使用 unshift 在陣列起始位置加入元素,也可以使用 slice 在陣列中間的地方加入元素。 +tip-tldr: 在一個存在的陣列加入新的元素是一件很常見的事情,你可以使用 push 將元素加入到陣列的末端,或是使用 unshift 在陣列起始位置加入元素,也可以使用 splice 在陣列中間的地方加入元素。 categories: - zh_TW --- -在一個存在的陣列加入新的元素是一件很常見的事情,你可以使用 push 將元素加入到陣列的末端,或是使用 unshift 在陣列起始位置加入元素,也可以使用 slice 在陣列中間的地方加入元素。 +# 在存在的陣列加入新的元素 + +在一個存在的陣列加入新的元素是一件很常見的事情,你可以使用 push 將元素加入到陣列的末端,或是使用 unshift 在陣列起始位置加入元素,也可以使用 splice 在陣列中間的地方加入元素。 那些都是已知的方法,但這並不代表沒有更好的效能的方法。讓我們開始吧: -在陣列的末端加入元素我們可以簡單地透過 push() 方式,但以下是更能提升效能方法。 +## 在陣列最後加入新的元素 + +在陣列最後加入新的元素我們可以簡單地透過 push() 方式,但以下是更能提升效能方法。 ```javascript var arr = [1, 2, 3, 4, 5]; +var arr2 = []; arr.push(6); -arr[arr.length] = 6; // 在 Mac OS X 10.11.1 下的 Chrome 47.0.2526.106 加快了 43% +arr[arr.length] = 6; +arr2 = arr.concat([6]); ``` 這兩種方法都是修改原始的陣列。不相信嗎?請參考 [jsperf](http://jsperf.com/push-item-inside-an-array)。 -現在,如果我們要嘗試在陣列的起始位置加入元素: +### 在 mobile 上的性能表現: + +#### Android (v4.2.2) + +1. _arr.push(6);_ 和 _arr[arr.length] = 6;_ 有相同的性能表現 // 3 319 694 ops/sec +3. _arr2 = arr.concat([6]);_ 較以上兩個方法慢 50.61 % + +#### Chrome Mobile (v33.0.0) + +1. _arr[arr.length] = 6;_ // 6 125 975 ops/sec +2. _arr.push(6);_ 慢 66.74 % +3. _arr2 = arr.concat([6]);_ 慢 87.63 % + +#### Safari Mobile (v9) + +1. _arr[arr.length] = 6;_ // 7 452 898 ops/sec +2. _arr.push(6);_ 慢 40.19 % +3. _arr2 = arr.concat([6]);_ 慢 49.78 % + +```javascript +最後勝利者 + +1. arr[arr.length] = 6; // 平均 5 632 856 ops/sec +2. arr.push(6); // 慢 35.64 % +3. arr2 = arr.concat([6]); // 慢 62.67 % +``` + +### 在 desktop 的性能表現 + +#### Chrome (v48.0.2564) + +1. _arr[arr.length] = 6;_ // 21 602 722 ops/sec +2. _arr.push(6);_ 慢 61.94 % +3. _arr2 = arr.concat([6]);_ 慢 87.45 % + +#### Firefox (v44) + +1. _arr.push(6);_ // 56 032 805 ops/sec +2. _arr[arr.length] = 6;_ 慢 0.52 % +3. _arr2 = arr.concat([6]);_ 慢 87.36 % + +#### IE (v11) + +1. _arr[arr.length] = 6;_ // 67 197 046 ops/sec +2. _arr.push(6);_ 慢 39.61 % +3. _arr2 = arr.concat([6]);_ 慢 93.41 % + +#### Opera (v35.0.2066.68) + +1. _arr[arr.length] = 6;_ // 30 775 071 ops/sec +2. _arr.push(6);_ 慢 71.60 % +3. _arr2 = arr.concat([6]);_ 慢 83.70 % + +#### Safari (v9.0.3) + +1. _arr.push(6);_ // 42 670 978 ops/sec +2. _arr[arr.length] = 6;_ 慢 0.80 % +3. _arr2 = arr.concat([6]);_ 慢 76.07 % + +```javascript +最後勝利者 + +1. arr[arr.length] = 6; // 平均 42 345 449 ops/sec +2. arr.push(6); // 慢 34.66 % +3. arr2 = arr.concat([6]); // 慢 85.79 % +``` + +## 在陣列起始加入元素 + +現在我們嘗試在陣列的起始加入元素: ```javascript var arr = [1, 2, 3, 4, 5]; arr.unshift(0); -[0].concat(arr); // 在 Mac OS X 10.11.1 下的 Chrome 47.0.2526.106 加快了 98% +[0].concat(arr); +``` +這裡有更多小細項:unshift 修改原始陣列;concat 回傳一個新的陣列。[jsperf](http://jsperf.com/unshift-item-inside-an-array) + +### 在 mobile 的性能表現: + +#### Android (v4.2.2) + +1. _[0].concat(arr);_ // 1 808 717 ops/sec +2. _arr.unshift(0);_ 慢 97.85 % + +#### Chrome Mobile (v33.0.0) + +1. _[0].concat(arr);_ // 1 269 498 ops/sec +2. _arr.unshift(0);_ 慢 99.86 % + +#### Safari Mobile (v9) + +1. _arr.unshift(0);_ // 3 250 184 ops/sec +2. _[0].concat(arr);_ 慢 33.67 % + +```javascript +最後勝利者 + +1. [0].concat(arr); // 平均 4 972 622 ops/sec +2. arr.unshift(0); // 慢 64.70 % +``` + +### 在 desktop 的性能表現 + +#### Chrome (v48.0.2564) + +1. _[0].concat(arr);_ // 2 656 685 ops/sec +2. _arr.unshift(0);_ 慢 96.77 % + +#### Firefox (v44) + +1. _[0].concat(arr);_ // 8 039 759 ops/sec +2. _arr.unshift(0);_ 慢 99.72 % + +#### IE (v11) + +1. _[0].concat(arr);_ // 3 604 226 ops/sec +2. _arr.unshift(0);_ 慢 98.31 % + +#### Opera (v35.0.2066.68) + +1. _[0].concat(arr);_ // 4 102 128 ops/sec +2. _arr.unshift(0);_ 慢 97.44 % + +#### Safari (v9.0.3) + +1. _arr.unshift(0);_ // 12 356 477 ops/sec +2. _[0].concat(arr);_ 慢 15.17 % + +```javascript +最後勝利者 + +1. [0].concat(arr); // 平均 6 032 573 ops/sec +2. arr.unshift(0); // 慢 78.65 % ``` -這裡有更多的小細節:使用 unshift 修改原始的陣列;concat 返回新的陣列。 [jsperf](http://jsperf.com/unshift-item-inside-an-array) -使用 splice 陣列的中間加入元素是相當容易的,而且是最高效的方法。 +## 在陣列中間加入元素 + +在陣列中間可以簡單透過 splice 來加入元素,這樣的做法是最具效能的方式。 ```javascript var items = ['one', 'two', 'three', 'four']; items.splice(items.length / 2, 0, 'hello'); ``` -我嘗試在不同的瀏覽器和 OS 執行這些測試,他們的結果是相似的。我希望這些知識對你是有幫助的,也鼓勵你自己進行測試! +我嘗試在不同的瀏覽器和 OS 執行這些測試,他們的結果是相似的。我希望這些知識對你是有幫助的,也鼓勵你自己進行測試! \ No newline at end of file diff --git a/_posts/zh_TW/2016-01-01-angularjs-digest-vs-apply.md b/_posts/zh_TW/2016-01-01-angularjs-digest-vs-apply.md index c0957b22..06d01b98 100644 --- a/_posts/zh_TW/2016-01-01-angularjs-digest-vs-apply.md +++ b/_posts/zh_TW/2016-01-01-angularjs-digest-vs-apply.md @@ -20,11 +20,11 @@ AngularJs 最令人欣賞的特性之一是雙向資料綁定。AngularJS 透過 這個核心方法可以讓你明確地啟動 `$digest` 循環。意思說所有的 watchers 都會被確認;整個應用程式啟動 `$digest loop`。在內部,執行一個可選的功能參數,它會呼叫 `$rootScope.$digest();`。 ### `$digest` -在這個情況下,`$digest` 方法在目前的作用域和子作用域啟動 `$digeset` 循環。你應該注意到父作用域不會被確認,也不會受影響。 +在這個情況下,`$digest` 方法在目前的 scope 和子 scope 啟動 `$digeset` 循環。你應該注意到父 scope 不會被檢查,也不會受影響。 ### 建議 -- 當瀏覽器 DOM 事件在 AngularJS 之外被觸發使用 `$apply` 或 `$digest`。 -- 傳送一個函數表達式給 `$apply`,這裡有一個錯誤處理機制,並且允許整合在 `$digest` 循環的變化。 +- 當瀏覽器 DOM 事件觸發外部的 AngularJS 使用 `$apply` 或 `$digest`。 +- 傳送一個函式表達式給 `$apply`,這裡有一個錯誤處理機制,並且允許整合所有在 `$digest` 循環的變化。 ```javascript $scope.$apply(() => { @@ -32,6 +32,6 @@ $scope.$apply(() => { }); ``` -- 如果你只要更新目前的作用域和子作用域,使用 `$digest`,以及防止在整個應用程式執行新的 digest 循環。這在性能上的好處是相當明顯的。 -- `$apply()` 對電腦來說是一個相當困難的處理程序,如果過多的綁定會造成性能上的問題。 +- 如果你只要更新目前的 scope 和子 scope,使用 `$digest` 防止在整個應用程式執行新的 digest 循環。這在性能上的好處是相當明顯的。 +- `$apply()` 對電腦來說是一個相當複雜的處理程序,如果過多的 binding 會造成性能上的問題。 - 如果你使用 >AngularJS 1.2.X,使用 `$evalAsync`,這是一個核心方法,可以在目前的循環或下一個循環執行表達式,可以增加你的應用程式效能。 diff --git a/_posts/zh_TW/2016-01-02-keys-in-children-components-are-important.md b/_posts/zh_TW/2016-01-02-keys-in-children-components-are-important.md index d54f58e5..bc8ef7a5 100644 --- a/_posts/zh_TW/2016-01-02-keys-in-children-components-are-important.md +++ b/_posts/zh_TW/2016-01-02-keys-in-children-components-are-important.md @@ -5,15 +5,15 @@ title: 在子元件 Keys 是很重要的 tip-number: 02 tip-username: loverajoel tip-username-profile: https://github.com/loverajoel -tip-tldr: 從陣列中動態建立所有元件時,你必須傳送 key 屬性。它是一個唯一以及固定的 id,React 用來識別 DOM 裡面的每個元件,並區別它是否為同一個元件。使用 keys 可以確保子元件不會被重覆建立,也可以防止奇怪的事件發生。 +tip-tldr: 你可以從陣列動態建立 key 屬性並傳送到所有的元件(component)。它是一個唯一以及固定的 id,React 用來識別 DOM 裡面的每個元件,並區別它是否為同一個元件。使用 keys 可以確保子元件被保護而不會被重覆建立,也可以防止奇怪的事件發生。 categories: - zh_TW --- -從陣列中動態建立所有元件時,你必須傳送 [key](https://facebook.github.io/react/docs/multiple-components.html#dynamic-children) 屬性。它是一個唯一以及固定的 id,React 用來識別 DOM 裡面的每個元件,並區別它是否為同一個元件。使用 keys 可以確保子元件不會被重覆建立,也可以防止奇怪的事件發生。 +你可以從陣列動態建立 [key](https://facebook.github.io/react/docs/multiple-components.html#dynamic-children) 屬性並傳送到所有的元件(component)。它是一個唯一以及固定的 id,React 用來識別 DOM 裡面的每個元件,並區別它是否為同一個元件。使用 keys 可以確保子元件被保護而不會被重覆建立,也可以防止奇怪的事件發生。 -> Key 跟效能不太相關,它跟元件識別有關係(反之,它間接提升了效能)。隨機賦值和改變數值將無法識別。[Paul O’Shannessy](https://github.com/facebook/react/issues/1342#issuecomment-39230939) +> Key 跟效能不太相關,它跟元件識別較有關係(反之,它間接提升了效能)。隨機賦值和改變數值將無法識別。[Paul O’Shannessy](https://github.com/facebook/react/issues/1342#issuecomment-39230939) - 使用物件內存在的唯一值。 - 在你的父元件定義 keys,而不是子元件。 diff --git a/_posts/zh_TW/2016-01-03-improve-nested-conditionals.md b/_posts/zh_TW/2016-01-03-improve-nested-conditionals.md index 89f62566..798c923d 100644 --- a/_posts/zh_TW/2016-01-03-improve-nested-conditionals.md +++ b/_posts/zh_TW/2016-01-03-improve-nested-conditionals.md @@ -1,17 +1,17 @@ --- layout: post -title: 改善嵌套的條件式 +title: 改善巢狀化的條件式 tip-number: 03 tip-username: AlbertoFuente tip-username-profile: https://github.com/AlbertoFuente -tip-tldr: 我們要如何在 javascript 改善並更有效的嵌套 `if` 條件式? +tip-tldr: 我們要如何在 JavaScript 改善巢狀化的 `if` 條件式? categories: - zh_TW --- -我們要如何在 javascript 改善並更有效的嵌套 `if` 條件式? +我們要如何在 JavaScript 改善巢狀化的 `if` 條件式? ```javascript if (color) { @@ -29,7 +29,7 @@ if (color) { } ``` -有一種方式可以改善嵌套 `if` 條件式是使用 `switch` 陳述式。雖然簡潔,而且有排序,但是不建議使用,因為它不容易 debug 錯誤。告訴你[為什麼](https://toddmotto.com/deprecating-the-switch-statement-for-object-literals)。 +有一種方式可以改善巢狀化的 `if` 條件式是使用 `switch` 陳述式。雖然更簡潔有序,但是不建議使用,因為它不容易 debug 錯誤。告訴你[為什麼](https://toddmotto.com/deprecating-the-switch-statement-for-object-literals)。 ```javascript switch(color) { @@ -50,7 +50,7 @@ switch(color) { } ``` -但是,如果我們語句中都有很多條件檢查呢?在這個情況下,如果我們想要讓它更簡潔,而且有排序,我們可以使用有條件的 `switch`。 +但是,如果我們語句中都有很多條件檢查呢?在這個情況下,如果我們想要讓它更簡潔有序,我們可以使用有條件的 `switch`。 如果我們傳送 `true` 當作參數給 `switch` 陳述式,允許我們在每個 case 下使用條件式。 ```javascript @@ -89,4 +89,4 @@ if (color in colorObj) { } ``` -這裡你可以找到更多的資訊關於 [switch](http://www.nicoespeon.com/en/2015/01/oop-revisited-switch-in-js/。 +這裡你可以找到更多的資訊關於 [switch](http://www.nicoespeon.com/en/2015/01/oop-revisited-switch-in-js/)。 diff --git a/_posts/zh_TW/2016-01-05-differences-between-undefined-and-null.md b/_posts/zh_TW/2016-01-05-differences-between-undefined-and-null.md index ef878bc5..940dcc12 100644 --- a/_posts/zh_TW/2016-01-05-differences-between-undefined-and-null.md +++ b/_posts/zh_TW/2016-01-05-differences-between-undefined-and-null.md @@ -11,14 +11,14 @@ categories: - zh_TW --- -- `undefined` 意思是變數沒有被宣告,或者是已經宣告了,但是沒有賦予值。 -- `null` 意思是賦予「沒有值」的值。 -- Javascript 將未賦予值的變數的預設值設為 `undefined`。 +- `undefined` 意思是變數沒有被宣告,或者是已經宣告了,但是沒有賦值。 +- `null` 意思是「沒有值」的值。 +- Javascript 將未賦值的變數的預設值設為 `undefined`。 - Javascript 從來不會將值設定為 `null`。這是讓開發者用來宣告 `var` 是沒有值的。 - `undefined` 不是一個有效的 JSON,而 `null` 是有效的。 - `undefined` 的類型(typeof) 是 `undefined`。 - `null` 的類型(typeof)是一個 `object`。[為什麼?](http://www.2ality.com/2013/10/typeof-null.html) -- 它們都是資料元素。 +- 它們都是原始(primitives)型別。 - 它們都是 [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) (`Boolean(undefined) // false`, `Boolean(null) // false`)。 - 你可以判斷一個變數是否為 [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)。 diff --git a/_posts/zh_TW/2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md b/_posts/zh_TW/2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md index bb9a90f8..43f32664 100644 --- a/_posts/zh_TW/2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md +++ b/_posts/zh_TW/2016-01-06-writing-a-single-method-for-arrays-and-a-single-element.md @@ -5,13 +5,13 @@ title: 撰寫一個可以接受單一參數和陣列的方法 tip-number: 06 tip-username: mattfxyz tip-username-profile: https://twitter.com/mattfxyz -tip-tldr: 撰寫你的函式可以處理陣列或單一元素參數,而不是透過分開的方法來處理陣列和單一元素參數。這和 jQuery 一些函式工作原理相似(`css` selector 將會修改所有匹配的)。 +tip-tldr: 你撰寫的函式要可以處理陣列或單一元素參數,而不是透過分開的方法來處理陣列和單一元素參數。這和 jQuery 一些函式工作原理相似(`css` 將會修改所有和 selector matched 的)。 categories: - zh_TW --- -撰寫你的函式可以處理陣列或單一元素參數,而不是透過分開的方法來處理陣列和單一元素參數。這和 jQuery 一些函式工作原理相似(`css` selector 將會修改所有匹配的)。 +你撰寫的函式要可以處理陣列或單一元素參數,而不是透過分開的方法來處理陣列和單一元素參數。這和 jQuery 一些函式工作原理相似(`css` 將會修改所有和 selector matched 的)。 首先,你只要將任何的東西 concat 到陣列上。`Array.concat` 將會接受陣列或是單一元素。 @@ -24,7 +24,7 @@ function printUpperCase(words) { } ``` -`printUpperCase` 現在已經可以接收單一文字或是多個文字的陣列當作它的參數了。 +`printUpperCase` 現在已經可以接收單一的 node 或是一個陣列 nodes 當作它的參數了。 ```javascript printUpperCase("cactus"); diff --git a/_posts/zh_TW/2016-01-07-use-strict-and-get-lazy.md b/_posts/zh_TW/2016-01-07-use-strict-and-get-lazy.md index e3fb7264..12c54164 100644 --- a/_posts/zh_TW/2016-01-07-use-strict-and-get-lazy.md +++ b/_posts/zh_TW/2016-01-07-use-strict-and-get-lazy.md @@ -13,9 +13,9 @@ categories: JavaScript 嚴格模式讓開發者可以寫出更「安全」的 JavaScript 程式碼。 -預設情況下,JavaScript 允許開發者的粗心行為,例如,當我們引用一個沒有要求我們由「var」宣告的變數。或許這個對於一個剛入門的開發者相當方便,當變數名稱拼寫錯誤或者是不小心參考到其他的範圍(scope),這些都是許多錯誤的來源。 +預設情況下,JavaScript 允許開發者的粗心行為,例如,當我們引用一個沒有要求我們由「var」宣告的變數。或許這個對於一個剛入門的開發者相當方便,當變數名稱拼寫錯誤或者是不小心參考到其他的 scope,這些都是許多錯誤的來源。 -開發者喜歡讓電腦幫我們做一些無聊的工作,然後自動地幫我們確認工作上的錯誤。這就是 JavaScript 的 「嚴格模式」(use strict)幫我們做的,將錯誤轉換成 JavaScript 錯誤。 +開發者喜歡讓電腦幫我們做一些無聊的工作,然後自動幫我們確認工作上的錯誤。這就是 JavaScript 的 「嚴格模式」(use strict)幫我們做的,將錯誤轉換成 JavaScript 錯誤。 我們把這個指令放在 js 檔案的頂端: @@ -25,12 +25,12 @@ JavaScript 嚴格模式讓開發者可以寫出更「安全」的 JavaScript 程 var v = "Hi! I'm a strict mode script!"; ``` -或是在 function 內: +或是在函式內: ```javascript function f() { - // Function 內使用嚴格模式 + // 函式內使用嚴格模式 'use strict'; function nested() { return "And so am I!"; } return "Hi! I'm a strict mode function! " + nested(); @@ -38,11 +38,11 @@ function f() function f2() { return "I'm not strict."; } ``` -透過 JavaScript 檔案或 function 內引入這個指令,我們直接讓 JavaScript 引擎執行嚴格模式來禁止一些在大型 JavaScript 專案不良的行為。除了其他之外,嚴格模式改變了以下的行為: +透過 JavaScript 檔案或函式內引入這個指令,我們直接讓 JavaScript 引擎執行嚴格模式來禁止一些在大型 JavaScript 專案不良的行為。除了其他之外,嚴格模式改變了以下的行為: * 只有被宣告的「var」變數才可以被引用。 * 嘗試寫入唯讀的變數會造成錯誤。 -* 你只能透過「new」關鍵字才可以呼叫建構子。 +* 你只能透過「new」keyword 才可以呼叫建構子。 * 「this」不再隱式的綁定到全域的物件。 * 對 eval() 有嚴格的限制。 * 防止你使用保留字元或特殊字元當作變數名稱。 diff --git a/_posts/zh_TW/2016-01-08-converting-a-node-list-to-an-array.md b/_posts/zh_TW/2016-01-08-converting-a-node-list-to-an-array.md index b5af224a..00b6741f 100644 --- a/_posts/zh_TW/2016-01-08-converting-a-node-list-to-an-array.md +++ b/_posts/zh_TW/2016-01-08-converting-a-node-list-to-an-array.md @@ -5,39 +5,39 @@ title: 將 Node List 轉換成陣列 tip-number: 08 tip-username: Tevko tip-username-profile: https://twitter.com/tevko -tip-tldr: 這是將 Node List 轉換成 DOM 元素陣列的快速、安全以及可複用的方法。 +tip-tldr: 這是快速,安全,可重複使用的方式,將 Node List 轉換成 DOM 元素的陣列。 categories: - zh_TW --- -`querySelectorAll` 方法回傳一個類似陣列的物件稱為 Node List。這些資料結構簡稱為「類陣列」,因為他們和陣列很相似,但是不能使用陣列的方法像是 `map` 和 `forEach`。這是將 Node List 轉換成 DOM 元素陣列的快速、安全以及可複用的方法: +`querySelectorAll` 方法回傳一個類似陣列的物件稱為 Node List。這些資料結構簡稱為「類陣列」,因為他們和陣列很相似,但是不能使用陣列的方法像是 `map` 和 `forEach`。這是快速,安全,可重複使用的方式,將 Node List 轉換成 DOM 元素的陣列: ```javascript const nodelist = document.querySelectorAll('div'); const nodelistToArray = Array.apply(null, nodelist); -//之後 .. +// 之後 .. nodelistToArray.forEach(...); nodelistToArray.map(...); nodelistToArray.slice(...); -//等等... +// 等等... ``` -`apply` 方法使用在將給定的 `this` 數值傳送到給定的函式參數陣列。根據 [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) ,`apply` 採用類陣列物件,而這剛好就是 `querySelectorAll` 方法所回傳的內容。如果我們不需要在函式的上下文(context)中指定 `this` ,我們可以傳送 `null` 或 `0`。這個結果實際上是一個 DOM 元素陣列,包含所有可用的陣列方法。 +`apply` 方法將參數陣列傳送給一個函式與給定 this 的值。根據 [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) ,`apply` 採用類陣列物件,而這剛好就是 `querySelectorAll` 方法所回傳的內容。如果我們不需要在函式的上下文(context)中指定 `this` ,我們可以傳送 `null` 或 `0`。這個結果實際上是一個 DOM 元素陣列,包含所有可用的陣列方法。 或者,假設你使用 ES2015 你可以使用[展開運算符 `...`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)。 ```js const nodelist = [...document.querySelectorAll('div')]; // 回傳一個實際的陣列 -//之後 .. +// 之後 .. nodelist.forEach(...); nodelist.map(...); nodelist.slice(...); -//等等... +// 等等... ``` diff --git a/_posts/zh_TW/2016-01-09-template-strings.md b/_posts/zh_TW/2016-01-09-template-strings.md index 51e33493..59347681 100644 --- a/_posts/zh_TW/2016-01-09-template-strings.md +++ b/_posts/zh_TW/2016-01-09-template-strings.md @@ -1,17 +1,17 @@ --- layout: post -title: 樣板字串符 +title: 模板字串 tip-number: 09 tip-username: JakeRawr tip-username-profile: https://github.com/JakeRawr -tip-tldr: 在 ES6 中,JS 現在有了樣板字串元來替代原本我們使用的引號字元。 +tip-tldr: 由於 ES6 中有了模板字串,JavaScript 可以使用模板字串來替代原本我們使用的引號字元。 categories: - zh_TW --- -在 ES6 中,JS 現在有了樣板字串符來替代原本我們使用的引號字元。 +由於 ES6 中有了模板字串,JavaScript 可以使用模板字串來替代原本我們使用的引號字元。 Ex: 正常的字串 @@ -22,7 +22,7 @@ var lastName = 'Rawr'; console.log('My name is ' + firstName + ' ' + lastName); // My name is Jake Rawr ``` -樣板字串符 +模板字串 ```javascript var firstName = 'Jake'; @@ -31,7 +31,7 @@ console.log(`My name is ${firstName} ${lastName}`); // My name is Jake Rawr ``` -在樣板字串符,你不需要透過 `\n` 來產生多行的字串,只要簡單透過 `${}` 來替代就可以了,還可以計算簡單的邏輯,例如:`${2 + 3}`。 -你也可以使用函式來修改你的輸出的內容;例如使用標籤樣板字串符,它們被稱為[標籤樣板字串符](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings#Tagged_template_strings)。 +在模板字串中,你不需要透過 `\n` 來產生多行的字串,只要簡單透過 `${}` 來替代就可以了,還可以計算簡單的邏輯,例如:`${2 + 3}`。 +你也可以使用函式來修改你的輸出的內容;例如使用標籤模板字串,它們被稱為[標籤模板字串](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings#Tagged_template_strings)。 -你或許想要[閱讀](https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2)和了解更多關於樣板字串符。 +你或許想要[閱讀](https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2)和了解更多關於模板字串。 diff --git a/_posts/zh_TW/2016-01-10-check-if-a-property-is-in-a-object.md b/_posts/zh_TW/2016-01-10-check-if-a-property-is-in-a-object.md index 75c12e1c..d3d45818 100644 --- a/_posts/zh_TW/2016-01-10-check-if-a-property-is-in-a-object.md +++ b/_posts/zh_TW/2016-01-10-check-if-a-property-is-in-a-object.md @@ -24,7 +24,7 @@ if (myObject.name) { ... } 以上的方法是沒問題的,但是你必須知道對於這個問題有兩個原生的方法,[`in` 運算符](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in)和 [`Object.hasOwnProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)。任何繼承 `Object` 的都可以使用這兩種方法。 -### 觀察較大的差別 +### 觀察之間較大的差別 ```javascript var myObject = { diff --git a/_posts/zh_TW/2016-01-11-hoisting.md b/_posts/zh_TW/2016-01-11-hoisting.md index 63faab3e..13c1c033 100644 --- a/_posts/zh_TW/2016-01-11-hoisting.md +++ b/_posts/zh_TW/2016-01-11-hoisting.md @@ -11,7 +11,7 @@ categories: - zh_TW --- -了解 [hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) 將會幫助你組織你的函式範圍。只要記得,變數宣告和函式定義都會被提升到頂端。變數定義則不會,即使你宣告和定義一個變數再同一行。變數**宣告**是讓系統知道變數的存在,而**定義**只是分配給它一個值。 +了解 [hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) 將會幫助你編寫函式 scope。只要記得,變數宣告和函式定義都會被提升到頂端。變數定義則不會,即使你宣告和定義一個變數再同一行。變數**宣告**是讓系統知道變數的存在,而**定義**只是分配給它一個值。 ```javascript function doTheThing() { @@ -48,4 +48,4 @@ function doTheThing() { } ``` -如果要讓你的程式碼更容易閱讀,將你所有的變數宣告在你的函式範圍頂端,這樣可以更清楚知道變數是來自哪個範圍。在你使用變數之前請先定義。在你的範圍底部定義函式,來保持它們的方式。 +為了讓你的程式碼更容易閱讀,將你所有的變數宣告在你的函式 scope 頂端,這樣可以更清楚知道變數是來自哪個 scope。在你使用變數之前請先定義。在你的 scope 底部定義函式,來保持它們的方式。 diff --git a/_posts/zh_TW/2016-01-13-tip-to-measure-performance-of-a-javascript-block.md b/_posts/zh_TW/2016-01-13-tip-to-measure-performance-of-a-javascript-block.md index f7867ae9..03f74efa 100644 --- a/_posts/zh_TW/2016-01-13-tip-to-measure-performance-of-a-javascript-block.md +++ b/_posts/zh_TW/2016-01-13-tip-to-measure-performance-of-a-javascript-block.md @@ -1,7 +1,7 @@ --- layout: post -title: 測量 JavaScript 程式碼區塊性能的小知識 +title: 測量 JavaScript 程式碼區塊性能的 tip tip-number: 13 tip-username: manmadareddy tip-username-profile: https://twitter.com/manmadareddy diff --git a/_posts/zh_TW/2016-01-14-fat-arrow-functions.md b/_posts/zh_TW/2016-01-14-fat-arrow-functions.md index b8dc5e59..00aa6182 100644 --- a/_posts/zh_TW/2016-01-14-fat-arrow-functions.md +++ b/_posts/zh_TW/2016-01-14-fat-arrow-functions.md @@ -5,7 +5,7 @@ title: 箭頭函式 tip-number: 14 tip-username: pklinger tip-username-profile: https://github.com/pklinger/ -tip-tldr: 介紹一個 ES6 的新特性,箭頭函式是一個方便的語法讓你用更少的程式碼做更多事。 +tip-tldr: 介紹一個 ES6 的新特性 - 箭頭函式是一個方便的語法讓你用更少的程式碼做更多事。 categories: - zh_TW @@ -42,11 +42,11 @@ var arrFunc = arr.map((x) => x*x); console.log(arr) ``` -正如你所見的,在這個範例箭頭函式省去了打出函式的括號和 return。我建議你在參數周圍寫出小括號,如果你需要多個輸入參數,像是 `(x,y) => x+y`。這是一個用來應付在不同情況下忘記使用小括號的方法。上面的程式碼也是這樣執行的:`x => x*x`。到目前為止,這些只是語法上的改進,減少的程式碼以及提高可讀性。 +正如你所見的,在這個範例箭頭函式省去了打出函式的括號和 return。我建議你在參數周圍寫出小括號,如果你需要多個輸入參數,像是 `(x, y) => x + y`。這是一個用來應付在不同情況下忘記使用小括號的方法。上面的程式碼也是這樣執行的:`x => x * x`。到目前為止,這些只是語法上的改進,減少的程式碼以及提高可讀性。 ### 詞彙綁定 - `this` -這是一個另一個更棒的理由來使用箭頭函式。這裡有一個 `this` 上下文(context)的問題。使用箭頭函數,你不需要擔心 `.bind(this)` 或設定 `that = this` 的問題了,在箭頭函式會幫你從詞彙的範圍綁定 `this` 的上下文。看以下的[範例](https://jsfiddle.net/pklinger/rw94oc11/): +這是一個另一個更棒的理由來使用箭頭函式。這裡有一個 `this` context 的問題。使用箭頭函數,你不需要擔心 `.bind(this)` 或設定 `that = this` 的問題了,在箭頭函式會幫你從詞彙的範圍綁定 `this` 的 context。看以下的[範例](https://jsfiddle.net/pklinger/rw94oc11/): ```javascript @@ -60,7 +60,7 @@ var counterD = new CounterD(); // bad example function CounterA() { - // CounterA 的 `this` 實例(!!調用時被忽略了) + // CounterA 的 `this` 實例(!!這裡被忽略了) this.i = 0; setInterval(function () { // `this` 參考到全域的物件,而不是 CounterA's 的 `this`, diff --git a/_posts/zh_TW/2016-01-16-passing-arguments-to-callback-functions.md b/_posts/zh_TW/2016-01-16-passing-arguments-to-callback-functions.md index 7c497211..a50f64e9 100644 --- a/_posts/zh_TW/2016-01-16-passing-arguments-to-callback-functions.md +++ b/_posts/zh_TW/2016-01-16-passing-arguments-to-callback-functions.md @@ -22,7 +22,7 @@ document.getElementById('someelem').addEventListener('click', callback); ``` -你在 JavaScript 利用閉包範圍的優點傳送參數給 callback 函式。看一下這個範例: +你可以利用 JavaScript 閉包(closure)scope 的優點傳送參數給 callback 函式。看一下這個範例: ```js function callback(a, b) { @@ -36,9 +36,9 @@ document.getElementById('someelem').addEventListener('click', callback(x, y)); ``` -### 什麼是閉包? +### 什麼是閉包(closure)? -閉包是指引用獨立(自由)變數的函式。換句話說,在閉包中定義的函式「記得」它被建立時的環境。在 [MDN 文件](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)了解更多。 +Closures 指的是一個獨立的變數函式。換句話說,在閉包中定義的函式「記得」它被建立時的環境。在 [MDN 文件](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)了解更多。 當 callback 函式被呼叫時,這些方法的參數 `x` 和 `y` 都會在 callback 函式的範圍內。 diff --git a/_posts/zh_TW/2016-01-17-nodejs-run-a-module-if-it-is-not-required.md b/_posts/zh_TW/2016-01-17-nodejs-run-a-module-if-it-is-not-required.md index 64fbbde8..2d77493a 100644 --- a/_posts/zh_TW/2016-01-17-nodejs-run-a-module-if-it-is-not-required.md +++ b/_posts/zh_TW/2016-01-17-nodejs-run-a-module-if-it-is-not-required.md @@ -5,13 +5,13 @@ title: Node.js - 執行尚未被 `required` 的模組 tip-number: 17 tip-username: odsdq tip-username-profile: https://twitter.com/odsdq -tip-tldr: 在 nodejs,你可以讓你的程式取決於 `require('./something.js')` 或 `node something.js` 這兩種不同的方式來執行你的程式碼。如果你想要在獨立的模組內使用,這是非常有用的。 +tip-tldr: 在 nodejs,你可以讓你的程式取決於 `require('./something.js')` 或 `node something.js` 這兩種不同的方式來執行你的程式碼。如果你想要將你的獨立模組交互使用是非常有用的。 categories: - zh_TW --- -在 nodejs,你可以讓你的程式取決於 `require('./something.js')` 或 `node something.js` 這兩種不同的方式來執行你的程式碼。如果你想要在獨立的模組內使用,這是非常有用的。 +在 nodejs,你可以讓你的程式取決於 `require('./something.js')` 或 `node something.js` 這兩種不同的方式來執行你的程式碼。如果你想要將你的獨立模組交互使用是非常有用的。 ```js if (!module.parent) { diff --git a/_posts/zh_TW/2016-01-18-rounding-the-fast-way.md b/_posts/zh_TW/2016-01-18-rounding-the-fast-way.md index 0350eb3d..cba6a0bd 100644 --- a/_posts/zh_TW/2016-01-18-rounding-the-fast-way.md +++ b/_posts/zh_TW/2016-01-18-rounding-the-fast-way.md @@ -5,15 +5,15 @@ title: 捨入最快的方法 tip-number: 18 tip-username: pklinger tip-username-profile: https://github.com/pklinger -tip-tldr: 今天的小知識是關於性能的部分。曾經使用過雙波浪 `~~` 運算符嗎?有時候也被稱為 雙 NOT 位元運算符。你可以使用它來替代 `Math.floor()` 更為快速。這是為什麼呢? +tip-tldr: 今天的 tip 是關於性能的部分。曾經使用過雙波浪 `~~` 運算符嗎?有時候也被稱為 雙 NOT 位元運算符。你可以使用它來替代 `Math.floor()` 更為快速。這是為什麼呢? categories: - zh_TW --- -今天的小知識是關於性能的部分。[曾經使用過雙波浪](http://stackoverflow.com/questions/5971645/what-is-the-double-tilde-operator-in-javascript) `~~` 運算符嗎?有時候也被稱為 雙 NOT 位元運算符。你可以使用它來替代 `Math.floor()` 更為快速。這是為什麼呢? +今天的 tip 是關於性能的部分。[曾經使用過雙波浪](http://stackoverflow.com/questions/5971645/what-is-the-double-tilde-operator-in-javascript) `~~` 運算符嗎?有時候也被稱為 雙 NOT 位元運算符。你可以使用它來替代 `Math.floor()` 更為快速。這是為什麼呢? -單位元移位運算符 `~` 將輸入的 32 位元轉換成 `-(input+1)`。因此,雙位元移位運算成為更好的工具,將輸入轉換成 `-(-(input + 1)+1)` 更趨近 0。對於數字輸入,負數就像使用 `Math.ceil()` 而正數就像使用 `Math.floor()`。若失敗的話,則回傳 `0`,當 `Math.floor()` 失敗回傳 `NaN` 時,或許此方法可以替代 `Math.floor()`。 +位元移位運算符 `~` 將輸入的 32 位元轉換成 `-(input+1)`。因此,雙位元移位運算成為更好的工具,將輸入轉換成 `-(-(input + 1)+1)` 更趨近 0。對於數字輸入,負數就像使用 `Math.ceil()` 而正數就像使用 `Math.floor()`。若失敗的話,則回傳 `0`,當 `Math.floor()` 失敗回傳 `NaN` 時,或許此方法可以替代 `Math.floor()`。 ```javascript // 單 ~ diff --git a/_posts/zh_TW/2016-01-19-safe-string-concatenation.md b/_posts/zh_TW/2016-01-19-safe-string-concatenation.md index cb022527..db81b75d 100644 --- a/_posts/zh_TW/2016-01-19-safe-string-concatenation.md +++ b/_posts/zh_TW/2016-01-19-safe-string-concatenation.md @@ -1,11 +1,11 @@ --- layout: post -title: 安全的字串串接 +title: 安全的使用字串串接 tip-number: 19 tip-username: gogainda tip-username-profile: https://twitter.com/gogainda -tip-tldr: 假設你有一些不確定的變數類型,而你想將它們串接成字串。可以肯定的是,算術運算符不是在串接過程的運用,請使用 concat。 +tip-tldr: 假設你有一些不確定的變數類型,而你想將它們串接成字串。可以確定的是,算術運算不是應用在串接的地方,使用 concat 來串接。 categories: - zh_TW @@ -18,7 +18,7 @@ var one = 1; var two = 2; var three = '3'; -var result = ''.concat(one, two, three); //"123" +var result = ''.concat(one, two, three); // "123" ``` 這個方法串接結果是你預期的。相反的,透過加號來串接會造成非預期的結果: @@ -28,7 +28,7 @@ var one = 1; var two = 2; var three = '3'; -var result = one + two + three; //"33" 而不是 "123" +var result = one + two + three; // "33" 而不是 "123" ``` 關於性能部分,與 `join` [類型](http://www.sitepoint.com/javascript-fast-string-concatenation/)比較,串接速度和 `concat` 是差不多的。 diff --git a/_posts/zh_TW/2016-01-20-return-objects-to-enable-chaining-of-functions.md b/_posts/zh_TW/2016-01-20-return-objects-to-enable-chaining-of-functions.md index 321078a4..bd50601a 100644 --- a/_posts/zh_TW/2016-01-20-return-objects-to-enable-chaining-of-functions.md +++ b/_posts/zh_TW/2016-01-20-return-objects-to-enable-chaining-of-functions.md @@ -1,17 +1,17 @@ --- layout: post -title: Return objects to enable chaining of functions回傳物件並使用函式鏈結 +title: 回傳物件並使用函式鏈結 tip-number: 20 tip-username: WakeskaterX tip-username-profile: https://twitter.com/WakeStudio -tip-tldr: 在 JavaScript 物件導向中,當函數回傳的物件中,讓你可以將函式鏈結在一起。 +tip-tldr: 在 JavaScript 物件導向中,我們在物件上建立函式,函式回傳的物件讓你可以將函式鏈結在一起。 categories: - zh_TW --- -在 JavaScript 物件導向中,當函數回傳的物件中,讓你可以將函式鏈結在一起。 +在 JavaScript 物件導向中,我們在物件上建立函式,函式回傳的物件讓你可以將函式鏈結在一起。 ```js function Person(name) { diff --git a/_posts/zh_TW/2016-01-21-shuffle-an-array.md b/_posts/zh_TW/2016-01-21-shuffle-an-array.md index 36926c4b..f19883b6 100644 --- a/_posts/zh_TW/2016-01-21-shuffle-an-array.md +++ b/_posts/zh_TW/2016-01-21-shuffle-an-array.md @@ -24,7 +24,7 @@ function shuffle(arr) { arr[i] = arr[j]; arr[j] = temp; } - return arr; + return arr; }; ``` 範例: diff --git a/_posts/zh_TW/2016-01-23-converting-to-number-fast-way.md b/_posts/zh_TW/2016-01-23-converting-to-number-fast-way.md index 6bfe9970..ce4f37a9 100644 --- a/_posts/zh_TW/2016-01-23-converting-to-number-fast-way.md +++ b/_posts/zh_TW/2016-01-23-converting-to-number-fast-way.md @@ -5,13 +5,13 @@ title: 轉換為數字更快的方式 tip-number: 23 tip-username: sonnyt tip-username-profile: http://twitter.com/sonnyt -tip-tldr: 轉換字串為數字是相當常見的。最簡單和快速的方式是使用 + 運算符來實現。 +tip-tldr: 轉換字串為數字是相當常見的。最簡單和快速的方式是使用 + 運算子來實現。 categories: - zh_TW --- -轉換字串為數字是相當常見的。最簡單和快速的方式是使用 `+` (加號)運算符來實現。([jsPref](https://jsperf.com/number-vs-parseint-vs-plus/29)) +轉換字串為數字是相當常見的。最簡單和快速的方式是使用 `+` (加號)運算子來實現。([jsPerf](https://jsperf.com/number-vs-parseint-vs-plus/29)) ```javascript var one = '1'; @@ -19,7 +19,7 @@ var one = '1'; var numberOne = +one; // Number 1 ``` -你也可以使用 `-` (減號)運算符將數字類型轉換成負數。 +你也可以使用 `-` (減號)運算子將數字類型轉換成負數。 ```javascript var one = '1'; diff --git a/_posts/zh_TW/2016-01-24-use_===_instead_of_==.md b/_posts/zh_TW/2016-01-24-use_===_instead_of_==.md index 65a0eace..3162e9fe 100644 --- a/_posts/zh_TW/2016-01-24-use_===_instead_of_==.md +++ b/_posts/zh_TW/2016-01-24-use_===_instead_of_==.md @@ -5,13 +5,13 @@ title: 使用 === 來替代 == tip-number: 24 tip-username: bhaskarmelkani tip-username-profile: https://www.twitter.com/bhaskarmelkani -tip-tldr: ==(或 !=)運算符如果在執行上需要的話,會自動將類型轉換。 `===`(或 `!==`)運算符則不會執行轉換。`===`(或 `!==`)用來比較數值和類型,相較於 `==` 更來的快速。 +tip-tldr: ==(或 !=)運算子如果在執行上需要的話,會自動將類型轉換。 `===`(或 `!==`)運算子則不會執行轉換。`===`(或 `!==`)用來比較數值和類型,相較於 `==` 更來的快速。 categories: - zh_TW --- -`==`(或 `!=`)運算符如果在執行上需要的話,會自動將類型轉換。 `===`(或 `!==`)運算符則不會執行轉換。`===`(或 `!==`)用來比較數值和類型,相較於 `==` 更來的快速。([jsPref](http://jsperf.com/strictcompare)) +`==`(或 `!=`)運算子如果在執行上需要的話,會自動將類型轉換。 `===`(或 `!==`)運算子則不會執行轉換。`===`(或 `!==`)用來比較數值和類型,相較於 `==` 更來的快速。([jsPref](http://jsperf.com/strictcompare)) ```js [10] == 10 // is true diff --git a/_posts/zh_TW/2016-01-25-Using-immediately-invoked-function-expression.md b/_posts/zh_TW/2016-01-25-Using-immediately-invoked-function-expression.md index f9c381cd..9d9a5be6 100644 --- a/_posts/zh_TW/2016-01-25-Using-immediately-invoked-function-expression.md +++ b/_posts/zh_TW/2016-01-25-Using-immediately-invoked-function-expression.md @@ -25,7 +25,7 @@ categories: 它是一個匿名函式表達式,而且可以立即被調用,在 JavaScript 某些部分中相當重要。 -一對括號包著匿名函式,將匿名函式變成函式表達式或變數表達式。我們現在有一個未命名的函式表達式,它不是一個在全域範圍內的簡單匿名函式或者是其他任何被定義的函式。 +一對括號包著匿名函式,將匿名函式變成函式表達式或變數表達式。我們現在有一個未命名的函式表達式,它不是一個在全域 scope 內的簡單匿名函式或者是其他任何被定義的函式。 同樣的,我們也可以為立即函式表達式命名: diff --git a/_posts/zh_TW/2016-01-26-filtering-and-sorting-a-list-of-strings.md b/_posts/zh_TW/2016-01-26-filtering-and-sorting-a-list-of-strings.md index aa042c1f..6ae32527 100644 --- a/_posts/zh_TW/2016-01-26-filtering-and-sorting-a-list-of-strings.md +++ b/_posts/zh_TW/2016-01-26-filtering-and-sorting-a-list-of-strings.md @@ -13,13 +13,13 @@ categories: 你可能有一份很大的清單,而你需要過濾重複的內容並移除,再依字母排序。 -在我們的範例,我使用了不同版本的 **JavaScript 保留字元** 的清單,但你要注意到,這裡有一些重複的字元而且他們不是依字母排序的。所以,這裡有一個相當棒的字串[陣列](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)清單來測試這個 JavaScript 小知識。 +在我們的範例,我使用了不同版本的 **JavaScript 保留字元** 的清單,但你要注意到,這裡有一些重複的字元而且他們不是依字母排序的。所以,這裡有一個相當棒的字串[陣列](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)清單來測試這個 JavaScript tip。 ```js var keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'var', 'case', 'else', 'enum', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'delete', 'export', 'import', 'return', 'switch', 'typeof', 'default', 'extends', 'finally', 'continue', 'debugger', 'function', 'do', 'if', 'in', 'for', 'int', 'new', 'try', 'var', 'byte', 'case', 'char', 'else', 'enum', 'goto', 'long', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'final', 'float', 'short', 'super', 'throw', 'while', 'delete', 'double', 'export', 'import', 'native', 'public', 'return', 'static', 'switch', 'throws', 'typeof', 'boolean', 'default', 'extends', 'finally', 'package', 'private', 'abstract', 'continue', 'debugger', 'function', 'volatile', 'interface', 'protected', 'transient', 'implements', 'instanceof', 'synchronized', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'await', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof']; ``` -因為我們不想改變我們原有的清單,所以我們使用高階函式叫做 [`filter`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),它會基於我們傳送的陣列(*function*)並回傳一個過濾後的新陣列。基於目前的清單和新的清單索引 `index` 的比較,會把和 index 相符的元素 push 到新陣列成為新的清單。 +因為我們不想改變我們原有的清單,所以我們使用高階函式叫做 [`filter`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),它會基於我們傳送的陣列(*函式*)並回傳一個過濾後的新陣列。基於目前的清單和新的清單索引 `index` 的比較,會把和 index 相符的元素 push 到新陣列成為新的清單。 最後,我們使用 [`sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) 函式來排序過濾後的結果,將比較函式當作唯一的參數,回傳依字母排序後的清單。 diff --git a/_posts/zh_TW/2016-01-27-short-circiut-evaluation-in-js.md b/_posts/zh_TW/2016-01-27-short-circiut-evaluation-in-js.md index b171f450..7aef864d 100644 --- a/_posts/zh_TW/2016-01-27-short-circiut-evaluation-in-js.md +++ b/_posts/zh_TW/2016-01-27-short-circiut-evaluation-in-js.md @@ -1,17 +1,17 @@ --- layout: post -title: JS 中的短路求值 +title: JavaScript 中的捷徑計算 tip-number: 27 tip-username: bhaskarmelkani tip-username-profile: https://www.twitter.com/bhaskarmelkani -tip-tldr: 短路求值意思是說,假設第一個參數不足以確定表達式的值,第二個參數才會被執行,當 AND(&&)函數的第一個參數計算結果為 false,則所有結果則為 false;當 OR(||)函數的第一個參數計算結果為 true,則所有結果為 true。 +tip-tldr: 捷徑計算意思是說,假設第一個參數不足以確定表達式的值,第二個參數才會被執行,當 AND 函數的第一個參數計算結果為 false,則所有結果則為 false;當 OR 函數的第一個參數計算結果為 true,則所有結果為 true。 categories: - zh_TW --- -[短路求值](https://en.wikipedia.org/wiki/Short-circuit_evaluation)意思是說,假設第一個參數不足以確定表達式的值,第二個參數才會被執行,當 AND(&&)函數的第一個參數計算結果為 false,則所有結果則為 false;當 OR(||)函數的第一個參數計算結果為 true,則所有結果為 true。 +[捷徑計算](https://en.wikipedia.org/wiki/Short-circuit_evaluation)意思是說,假設第一個參數不足以確定表達式的值,第二個參數才會被執行,當 AND 函數的第一個參數計算結果為 false,則所有結果則為 false;當 OR 函數的第一個參數計算結果為 true,則所有結果為 true。 對於以下的 `test` 條件和 `isTrue` 以及 `isFalse` 函式。 @@ -73,6 +73,6 @@ dog.bark(); // Woof Woof. // 但是如果 dog 尚未被定義,dog.bark() 將會發生「無法讀取尚未定義的屬性 'bark'」的錯誤。 // 為了防止這個問題,我們使用 &&。 -dog&&dog.bark(); // 如果 dog 被定義了,那我們就可以呼叫 dog.bark()。 +dog && dog.bark(); // 如果 dog 被定義了,那我們就可以呼叫 dog.bark()。 ``` diff --git a/_posts/zh_TW/2016-01-28-curry-vs-partial-application.md b/_posts/zh_TW/2016-01-28-curry-vs-partial-application.md index 95be6107..016975d0 100644 --- a/_posts/zh_TW/2016-01-28-curry-vs-partial-application.md +++ b/_posts/zh_TW/2016-01-28-curry-vs-partial-application.md @@ -5,7 +5,7 @@ title: 柯里化(currying)和部分應用程式 tip-number: 28 tip-username: bhaskarmelkani tip-username-profile: https://www.twitter.com/bhaskarmelkani -tip-tldr: 柯里化(currying)和部分應用程式(partial application)兩種方式是將函式轉換變成其他更小參數的函式。 +tip-tldr: 柯里化(currying)和部分應用程式(partial application)是將函式轉換成一般較小的 arity 和另一個函式的兩種方式。 categories: @@ -26,7 +26,7 @@ categories: 因此,未使用柯里化的函式 `f` 像這樣調用: -`f(3,5)` +`f(3, 5)` 如果使用柯里化後的函式 `f'` 像這樣調用: diff --git a/_posts/zh_TW/2016-01-30-converting-truthy-falsy-values-to-boolean.md b/_posts/zh_TW/2016-01-30-converting-truthy-falsy-values-to-boolean.md index 0a6ec5c2..fd60a739 100644 --- a/_posts/zh_TW/2016-01-30-converting-truthy-falsy-values-to-boolean.md +++ b/_posts/zh_TW/2016-01-30-converting-truthy-falsy-values-to-boolean.md @@ -5,14 +5,14 @@ title: 將 truthy 和 falsy 轉換成布林值 tip-number: 30 tip-username: hakhag tip-username-profile: https://github.com/hakhag -tip-tldr: 邏輯運算符是 JavaScript 核心之一 ,在這裡你可以發現這個方式,不管你給他什麼值,都會得到 true 或 false 。 +tip-tldr: 邏輯運算子是 JavaScript 核心之一 ,在這裡你可以發現這個方式,不管你給他什麼值,都會得到 true 或 false 。 categories: - zh_TW --- -你可以使用 `!!` 運算符將 [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) 或 [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) 轉換成布林值。 +你可以使用 `!!` 運算子將 [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) 或 [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) 轉換成布林值。 ```js !!"" // false diff --git "a/_posts/zh_TW/2016-01-31-avoid-modifying-or-passing-arguments-into-other-functions\342\200\224it-kills-optimization.md" "b/_posts/zh_TW/2016-01-31-avoid-modifying-or-passing-arguments-into-other-functions\342\200\224it-kills-optimization.md" index 6d5fc293..eb8a9344 100644 --- "a/_posts/zh_TW/2016-01-31-avoid-modifying-or-passing-arguments-into-other-functions\342\200\224it-kills-optimization.md" +++ "b/_posts/zh_TW/2016-01-31-avoid-modifying-or-passing-arguments-into-other-functions\342\200\224it-kills-optimization.md" @@ -19,7 +19,7 @@ categories: ```js var args = Array.prototype.slice.call(arguments); ``` -將 `arguments` 傳送到 `Array` 原型的上的 `slice` 方法;`slice` 方法回傳淺拷貝的 `arguments` 當作新的陣列物件。這共同簡寫的是: +將 `arguments` 傳送到 `Array` 原型的上的 `slice` 方法;`slice` 方法回傳淺拷貝的 `arguments` 當作新的陣列物件。一般常見的簡寫方法: ```js var args = [].slice.call(arguments); @@ -28,7 +28,7 @@ var args = [].slice.call(arguments); ### 優化 -不幸的是,傳送 `arguments` 到任何函式做呼叫,造成在 Chrome 和 Node 跳過 JavaScript V8 引擎的優化功能,這可能會導致性能降低。參考這篇 [optimization killers](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers) 文章。傳送 `arguments` 到函式稱為 *leaking `arguments`*。 +不幸的是,傳送到任何函式呼叫的 `arguments`,造成在 Chrome 和 Node 跳過 JavaScript V8 引擎的優化功能,這可能會導致性能降低。參考這篇 [optimization killers](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers) 文章。傳送 `arguments` 到函式稱為 *leaking `arguments`*。 相反的,假設你需要包含參數的陣列,你可以藉助這個方法: diff --git a/_posts/zh_TW/2016-02-01-map-to-the-rescue-adding-order-to-object-properties.md b/_posts/zh_TW/2016-02-01-map-to-the-rescue-adding-order-to-object-properties.md index 838848aa..773ba1b7 100644 --- a/_posts/zh_TW/2016-02-01-map-to-the-rescue-adding-order-to-object-properties.md +++ b/_posts/zh_TW/2016-02-01-map-to-the-rescue-adding-order-to-object-properties.md @@ -5,7 +5,7 @@ title: 透過 Map() 在你的物件屬性加入排序 tip-number: 32 tip-username: loverajoel tip-username-profile: https://twitter.com/loverajoel -tip-tldr: 物件是一個沒有排序的屬性集合...意思說,假設你想嘗試在你的物件內將資料做排序,你需要要重新做排序,因為屬性在物件不保證是有排序的。 +tip-tldr: 物件是一個沒有排序的屬性集合...意思說,如果你想嘗試在你的物件儲存已排序的資料,你需要重新檢查,因為屬性在物件不保證是有排序的。 categories: - zh_TW @@ -34,13 +34,13 @@ for (item in myObject) {... // @ // b ``` -因為技術關係,每個瀏覽器有自己排序物件的規則,所以順序是不確定的。 +因為每個瀏覽器有自己排序物件的規則,所以順序是不確定的。 ## 要如何解決這個問題? ### Map -使用 ES6 的新特性 - Map。 [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) 物件迭代元素插入的順序。`for...of` 迴圈每次迭代回傳一個 [key, value] 的陣列。 +使用 ES6 的新特性 - Map。[Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) 物件迭代元素插入的順序。`for...of` 迴圈每次迭代回傳一個 [key, value] 的陣列。 ```js var myObject = new Map(); diff --git a/_posts/zh_TW/2016-02-02-create-range-0...n-easily-using-one-line.md b/_posts/zh_TW/2016-02-02-create-range-0...n-easily-using-one-line.md index 97ee0663..92499c40 100644 --- a/_posts/zh_TW/2016-02-02-create-range-0...n-easily-using-one-line.md +++ b/_posts/zh_TW/2016-02-02-create-range-0...n-easily-using-one-line.md @@ -18,7 +18,7 @@ categories: Array.apply(null, {length: N}).map(Number.call, Number); ``` -讓我們來拆解這行程式碼。我們知道 `call` 函式可以在 JavaScript 執行,所以,在 `call` 第一個參數是上下文(context),而第二個參數開始則是呼叫 `call` 函式所需要用到的參數。 +讓我們來拆解這行程式碼。我們知道 `call` 函式可以在 JavaScript 執行。所以,在 `call` 第一個參數是上下文(context),而第二個參數開始則是呼叫 `call` 函式所需要用到的參數。 ```js function add(a, b){ @@ -28,7 +28,7 @@ add.call(null, 5, 6); ``` 回傳 5 和 6 的總和。 -在 JavaScript 陣列的 `map()` 帶有兩個參數,第一個是 `callback`,第二個則是 `thisArg(context)`。`callback` 中帶有三個參數,`value`、`index` 以及整個要被迭代的陣列。一般語法像是這樣: +在 JavaScript 陣列的 `map()` 帶有兩個參數,第一個是 `callback`,第二個則是 `thisArg(context)`。`callback` 中帶有三個參數,`value`、`index` 以及整個要被迭代的陣列。常見的語法像是這樣: ```js [1, 2, 3].map(function(value, index, arr){ @@ -50,6 +50,6 @@ Array.apply(null, {length: N}).map(Number.call, Number); ```js Array.apply(null, {length: N}).map(function(value, index){ - return index + 1; + return index + 1; }); ``` diff --git a/_posts/zh_TW/2016-02-03-implementing-asynchronous-loops.md b/_posts/zh_TW/2016-02-03-implementing-asynchronous-loops.md index 2db04521..9428ce55 100644 --- a/_posts/zh_TW/2016-02-03-implementing-asynchronous-loops.md +++ b/_posts/zh_TW/2016-02-03-implementing-asynchronous-loops.md @@ -17,8 +17,8 @@ categories: for (var i = 0; i < 5; i++) { setTimeout(function(){ console.log(i); - }, 1000); -} + }, 1000 * (i + 1)); +} ``` 上面的程式將會輸出以下的結果: @@ -42,8 +42,8 @@ for (var i = 0; i < 5; i++) { var temp = i; setTimeout(function(){ console.log(temp); - }, 1000); -} + }, 1000 * (i + 1)); +} ``` 但以上的程式輸出的結果是: @@ -55,7 +55,7 @@ for (var i = 0; i < 5; i++) { > 4 ``` -所以,一樣不能執行,因為區塊初始化時沒有建立一個範圍和變數,把它們提升到範圍的頂部。事實上,在前面的程式碼也是相同的: +所以,一樣不能執行,因為區塊初始化時沒有建立一個範圍和變數,把它們提升到 scope 的頂部。事實上,在前面的程式碼也是相同的: ```js var temp; @@ -63,21 +63,21 @@ for (var i = 0; i < 5; i++) { temp = i; setTimeout(function(){ console.log(temp); - }, 1000); -} + }, 1000 * (i + 1)); +} ``` **解決辦法** -這裡有一些不同的方式來複製 `i`。一般的方式是建立一個閉包,宣告一個函式並將 `i` 作為一個參數傳送。在這裡我們做了一個自我呼叫的函式。 +這裡有一些不同的方式來複製 `i`。一般的方式是建立一個 closure,宣告一個函式並將 `i` 作為一個參數傳送。在這裡我們做了一個立即函式。 ```js for (var i = 0; i < 5; i++) { (function(num){ setTimeout(function(){ console.log(num); - }, 1000); - })(i); -} + }, 1000 * (i + 1)); + })(i); +} ``` 在 JavaScript,參數是透過傳值方式給函數。所以原始的類型像是數字、日期、和字串基本上都是被複製的。如果你想要再函式內改變他們,它是不會影響外部的範圍。物件比較特別:假設內部函數改變屬性,這個改變會影響所有範圍。 @@ -88,6 +88,6 @@ for (let i = 0; i < 5; i++) { var temp = i; setTimeout(function(){ console.log(temp); - }, 1000); -} + }, 1000 * (i + 1)); +} ``` diff --git a/_posts/zh_TW/2016-02-04-assignment-shorthands.md b/_posts/zh_TW/2016-02-04-assignment-shorthands.md index 82f49a8e..07de3990 100644 --- a/_posts/zh_TW/2016-02-04-assignment-shorthands.md +++ b/_posts/zh_TW/2016-02-04-assignment-shorthands.md @@ -1,17 +1,17 @@ --- layout: post -title: 賦值運算符 +title: 賦值運算子 tip-number: 35 tip-username: hsleonis tip-username-profile: https://github.com/hsleonis -tip-tldr: 賦值是相當常見的。有時候我們這些「懶惰的開發者」覺得打字是很耗時得。所以我們使用一些技巧來幫助我們讓程式碼更乾淨簡單。 +tip-tldr: 賦值是相當常見的。有時候我們這些「懶惰的開發者」覺得打字是很耗時的。所以我們使用一些技巧來幫助我們讓程式碼更乾淨簡單。 categories: - zh_TW --- -賦值是相當常見的。有時候我們這些「懶惰的開發者」覺得打字是很耗時得。所以我們使用一些技巧來幫助我們讓程式碼更乾淨簡單。 +賦值是相當常見的。有時候我們這些「懶惰的開發者」覺得打字是很耗時的。所以我們使用一些技巧來幫助我們讓程式碼更乾淨簡單。 這是類似的方法 diff --git a/_posts/zh_TW/2016-02-05-observe-dom-changes.md b/_posts/zh_TW/2016-02-05-observe-dom-changes.md index 4abb0734..4fa2d537 100644 --- a/_posts/zh_TW/2016-02-05-observe-dom-changes.md +++ b/_posts/zh_TW/2016-02-05-observe-dom-changes.md @@ -11,7 +11,7 @@ tip-tldr: 由於現代動態的 JavaScript,當你在現有的網站開發擴 categories: - zh_TW --- -[MutationObserver](https://developer.mozilla.org/en/docs/Web/API/MutationObserver) 是一個監聽 DOM 的改變以及元素變化時的解決方法。在下面的範例是使用計時器模擬了內容動態載入,在第一個元素「target」建立後,接著建立「subTarget」。 +[MutationObserver](https://developer.mozilla.org/en/docs/Web/API/MutationObserver) 是一個 listen DOM 的改變以及元素變化時的解決方法。在下面的範例是使用計時器模擬了內容動態載入,在第一個元素「target」建立後,接著建立「subTarget」。 在擴充的程式碼中,首先 `rootObserver` 執行直到 `targetElement` 出現,然後 `elementObserver` 才開始執行。這個級聯觀察有助於直到最後發現 `subTargetElement`。 這個在開發擴充複雜的網站與動態內容載入時相當有用。 diff --git a/_posts/zh_TW/2016-02-06-deduplicate-an-array.md b/_posts/zh_TW/2016-02-06-deduplicate-an-array.md index f526b331..b13ab919 100644 --- a/_posts/zh_TW/2016-02-06-deduplicate-an-array.md +++ b/_posts/zh_TW/2016-02-06-deduplicate-an-array.md @@ -11,9 +11,9 @@ tip-tldr: 如何從陣列中移除不同資料類型重複的元素。 categories: - zh_TW --- -如果陣列只有包含基本數值,我們可以透過 + # 原始函數 -如果陣列只有包含基本數值,我們可以透過 [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) 和 [`indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) 方法來刪除重複的元素。 +如果陣列只有包含原始數值,我們可以透過 [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) 和 [`indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) 方法來刪除重複的元素。 ```javascript var deduped = [ 1, 1, 'a', 'a' ].filter(function (el, i, arr) { diff --git a/_posts/zh_TW/2016-02-07-flattening-multidimensional-arrays-in-javascript.md b/_posts/zh_TW/2016-02-07-flattening-multidimensional-arrays-in-javascript.md index 205de062..cfbd372a 100644 --- a/_posts/zh_TW/2016-02-07-flattening-multidimensional-arrays-in-javascript.md +++ b/_posts/zh_TW/2016-02-07-flattening-multidimensional-arrays-in-javascript.md @@ -1,7 +1,7 @@ --- layout: post -title: 在 JavaScript 中扁平化多維陣列 +title: 在 JavaScript 中將多維陣列扁平化 tip-number: 38 tip-username: loverajoel tip-username-profile: https://www.twitter.com/loverajoel @@ -55,6 +55,6 @@ console.log(myNewArray3); ``` 在[這裡](https://jsbin.com/qeqicu/edit?js,console)觀察三種方式的實際應用。 -對於無限嵌套陣列嘗試一下 Underscore 的 [flatten()](https://github.com/jashkenas/underscore/blob/master/underscore.js#L501)。 +對於較大的巢狀陣列可以嘗試使用 Underscore 的 [flatten()](https://github.com/jashkenas/underscore/blob/master/underscore.js#L501)。 -如果你好奇效能方面表現, [這裡](http://jsperf.com/flatten-an-array-loop-vs-reduce/6)有相關的測試。 +如果你好奇效能方面的表現, [這裡](http://jsperf.com/flatten-an-array-loop-vs-reduce/6)有相關的測試。 diff --git a/_posts/zh_TW/2016-02-08-advanced-properties.md b/_posts/zh_TW/2016-02-08-advanced-properties.md index 0869a94e..727b949e 100644 --- a/_posts/zh_TW/2016-02-08-advanced-properties.md +++ b/_posts/zh_TW/2016-02-08-advanced-properties.md @@ -41,10 +41,10 @@ Object.defineProperties(dest, { ``` 其中,包括以下可選的屬性: -- *value*:如果屬性不是 getter,數值是強制的屬性。`{a: 12}` === `Object.defineProperty(obj, 'a', {value: 12})` -- *writable*:將屬性設定為唯讀。請注意,如果該屬性是嵌套的物件,該屬性是仍然可以編輯。 +- *value*:如果屬性不是 getter(如下),數值是必要的屬性。`{a: 12}` === `Object.defineProperty(obj, 'a', {value: 12})` +- *writable*:將屬性設定為唯讀。請注意,如果該屬性是巢狀的物件,該屬性是仍然可以編輯。 - *enumerable*:將屬性設定為隱藏。這意思說,在 `for ... of` 迴圈和 `stringify` 的結果不包含屬性,但屬性仍然存在。注意:這不代表屬性為私有的!它依然可以從外部存取,它只是不會列印出來。 -- *configurable*:將屬性設定為不可修改。防止刪除或重新定義。再者,如果該屬性是一個嵌套的物件,其屬性仍然可以設定。 +- *configurable*:將屬性設定為不可修改。防止刪除或重新定義。再者,如果該屬性是一個巢狀的物件,其屬性仍然可以設定。 因此,為了建立一個私有的常數屬性,你像可以這樣定義: @@ -87,7 +87,7 @@ foobar.foo; // 15 foobar.foo = 20; // _foo = 20 ``` -除了經過封裝和存取的優點,你可以注意到我們沒有「呼叫」getter,相反的,我們只是「取得」不帶括號的屬性!這太棒了!舉個例子,讓我們想像我們有一個物件具有多層嵌套的屬性,像是: +除了有明顯的封裝和存取的優點,你可以注意到我們沒有「呼叫」getter,相反的,我們只是「取得」不帶括號的屬性!這太棒了!舉個例子,讓我們想像我們有一個物件具有多層巢狀的屬性,像是: ```js var obj = {a: {b: {c: [{d: 10}, {d: 20}] } } }; diff --git a/_posts/zh_TW/2016-02-09-using-json-stringify.md b/_posts/zh_TW/2016-02-09-using-json-stringify.md index 53f60b3a..8b164495 100644 --- a/_posts/zh_TW/2016-02-09-using-json-stringify.md +++ b/_posts/zh_TW/2016-02-09-using-json-stringify.md @@ -13,7 +13,7 @@ categories: --- 假設有一個物件有「prop1」、「prop2」、「prop3」屬性。 -我們傳送__附加參數__到 __JSON.stringify__ 將物件的屬性變成字串,像是: +我們傳送__額外的參數__到 __JSON.stringify__ 將物件的屬性變成字串,像是: ```javascript var obj = { diff --git a/_posts/zh_TW/2016-02-13-know-the-passing-mechanism.md b/_posts/zh_TW/2016-02-13-know-the-passing-mechanism.md index c7d3a799..45a982d7 100644 --- a/_posts/zh_TW/2016-02-13-know-the-passing-mechanism.md +++ b/_posts/zh_TW/2016-02-13-know-the-passing-mechanism.md @@ -5,12 +5,12 @@ title: 了解傳送機制 tip-number: 44 tip-username: bmkmanoj tip-username-profile: https://github.com/bmkmanoj -tip-tldr: JavaScript 技術上只傳送原始和物件類型的值(或參考值)。在參考類型的情況下,參考值本身是透過值來傳遞。 +tip-tldr: JavaScript 技術上只傳送原始和物件類型的值(或參考)。在參考的類型下,參考值本身是 passed by value。 categories: - zh_TW --- -JavaScript 技術上是透過傳值。它既不是傳值(pass-by-value)也不是傳參考(pass-by-reference),要理解這些術語的意義,你要了它們傳送的機制,透過以下的範例程式碼和解釋了解它們的意義。 +JavaScript 技術上是透過 pass-by-value。它既不是傳值(pass-by-value)也不是傳參考(pass-by-reference),要理解這些術語的意義,你要了它們傳送的機制,透過以下的範例程式碼和解釋了解它們的意義。 ### 範例一 @@ -25,14 +25,14 @@ function myTeam(me) { // 2 me = { // 3 'belongsTo' : 'A Group' }; -} +} -myTeam(me); +myTeam(me); console.log(me); // 4 : {'partOf' : 'A Team'} ``` -在上方的範例,當 `myTeam` 函式被調用,JavaScript *將 `me` 物件當作傳參考作為值*,調用本身建立了兩個獨立的參考在相同的物件,(雖然在這邊名稱相同,例如 `me`,這是一個誤導讓我們以為它是單一參考物件的印象。),因此,參考變數它們都是獨立的。 +在上方的範例,當 `myTeam` 函式被調用,JavaScript *將 `me` 物件當作 passing the reference 作為值*,調用本身建立了兩個獨立的參考在相同的物件,(雖然在這邊名稱相同,例如 `me`,這是一個誤導讓我們以為它是單一參考物件的印象。),因此,參考變數它們都是獨立的。 當我們在 #`3` 給了一個新的物件,我們完全改變 `myTeam` 函式內的參考值,在函式之外的原始物件不會受到影響,從這裡物件參考到外部保留了原始物件的值,並傳入函式內,因此可以從 #`4` 看到輸出值。 @@ -56,7 +56,7 @@ console.log(me); // 4 : {'partOf' : 'A Group'} 在這個例子 `myGroup` 被調用,我們傳送了物件 `me`。但不像範例一的程式碼,我們沒有給予 `me` 變數到任何的新物件,當我們在 `myGroup` 函式內修改物件的屬性,物件參考值一直是參考到原始的值,這是可以有效的改變物件的屬性。因此你可以從 #`7` 看到輸出值。 -所以最後一個情況也不能證明 JavaScript 是傳參考(pass-by-reference)嗎?不,它不是的。記住,*如果是物件的情況下,JavaScript 將傳參考作為值*。這裡會產生困惑,所以我們往往不能完全理解什麼是傳參考。這是明確的原因,有些人喜歡稱它們為 *call-by-sharing*。 +所以最後一個情況也不能證明 JavaScript 是 pass-by-reference 嗎?不,它不是的。記住,*如果是物件的情況下,JavaScript 將 passes the reference 作為值*。這裡會產生困惑,所以我們往往不能完全理解什麼是傳參考。這是明確的原因,有些人喜歡稱它們為 *call-by-sharing*。 *本文最早被作者發表於 [js-by-examples](https://github.com/bmkmanoj/js-by-examples/blob/master/examples/js_pass_by_value_or_reference.md)* diff --git a/_posts/zh_TW/2016-02-14-calculate-the-max-min-value-from-an-array.md b/_posts/zh_TW/2016-02-14-calculate-the-max-min-value-from-an-array.md index 66a0f02d..63ce9b16 100644 --- a/_posts/zh_TW/2016-02-14-calculate-the-max-min-value-from-an-array.md +++ b/_posts/zh_TW/2016-02-14-calculate-the-max-min-value-from-an-array.md @@ -30,7 +30,7 @@ Math.min.apply(null, numbers) // 1 傳送 `numbers` 陣列當作 `apply()` 的第二個參數,函式會呼叫陣列內所有的值當作函式的參數。 -更簡單的方式,透過 ES2015 的[展開運算符](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)來完成。 +更簡單的方式,透過 ES2015 的[展開運算子](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)來完成。 ```js var numbers = [1, 2, 3, 4]; @@ -38,4 +38,4 @@ Math.max(...numbers) // 4 Math.min(...numbers) // 1 ``` -這個操作符可以在函式的參數中把陣列內的數值「展開」。 +這個運算子可以在函式的參數中把陣列內的數值「展開」。 diff --git a/_posts/zh_TW/2016-02-15-detect-document-ready-in-pure-js.md b/_posts/zh_TW/2016-02-15-detect-document-ready-in-pure-js.md index 425b4426..e7e7e486 100644 --- a/_posts/zh_TW/2016-02-15-detect-document-ready-in-pure-js.md +++ b/_posts/zh_TW/2016-02-15-detect-document-ready-in-pure-js.md @@ -1,17 +1,17 @@ --- layout: post -title: 在純 JavaScript 檢查文件是否準備 +title: 使用 pure JavaScript 檢查文件是否準備 tip-number: 46 tip-username: loverajoel tip-username-profile: https://www.twitter.com/loverajoel -tip-tldr: 跨瀏覽器且使用純 JavaScript 來確認文件是否已經載入完成。 +tip-tldr: 可以跨瀏覽器,而且使用 pure JavaScript 來確認文件是否已經載入完成。 categories: - zh_TW --- -跨瀏覽器且使用純 JavaScript 來確認文件是否已經載入完成的方式是使用 [`readyState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState)。 +可以跨瀏覽器,而且使用 pure JavaScript 來確認文件是否已經載入完成的方式是使用 [`readyState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState)。 ```js if (document.readyState === 'complete') { diff --git a/_posts/zh_TW/2016-02-16-basics-declarations.md b/_posts/zh_TW/2016-02-16-basics-declarations.md index 13a7fc23..699f05b2 100644 --- a/_posts/zh_TW/2016-02-16-basics-declarations.md +++ b/_posts/zh_TW/2016-02-16-basics-declarations.md @@ -1,7 +1,7 @@ --- layout: post -title: 基礎宣告 +title: 宣告的基本知識 tip-number: 47 tip-username: adaniloff tip-username-profile: https://github.com/adaniloff diff --git a/_posts/zh_TW/2016-02-17-reminders-about-reduce-function-usage.md b/_posts/zh_TW/2016-02-17-reminders-about-reduce-function-usage.md index 88d4dfa2..f57a3d59 100644 --- a/_posts/zh_TW/2016-02-17-reminders-about-reduce-function-usage.md +++ b/_posts/zh_TW/2016-02-17-reminders-about-reduce-function-usage.md @@ -13,7 +13,7 @@ categories: 正如官方文件所寫的,`reduce()` 方法接收一個函式做為累加器(accumulator),陣列中的每個值(由左到右)將會合併,最後只得到一個值。 -### `reduce()` +### 署名 [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) 函式接受 2 個參數(M:強制的,O:可選的): @@ -22,7 +22,7 @@ categories: 所以讓我們來看一下普遍的用法,之後再看更多的複雜的用法。 -### 普遍用法(累加,關聯) +### 普遍用法(累加、關聯) 我們在逛 Amazon 網站(價格為美元),但是我們的 caddy 太滿了,所以讓我們計算總價。 @@ -31,7 +31,7 @@ categories: var items = [{price: 10}, {price: 120}, {price: 1000}]; // 我們的 reducer 函式 -var reducer = function add(sumSoFar, nextPrice) { return sumSoFar + nextPrice.price; }; +var reducer = function add(sumSoFar, item) { return sumSoFar + item.price; }; // 計算結果 var total = items.reduce(reducer, 0); @@ -60,8 +60,8 @@ console.log(total); // 1110 ```javascript var reducers = { totalInDollar: function(state, item) { - state.dollars += item.price; - return state; + // 具體宣告... + return state.dollars += item.price; }, totalInEuros : function(state, item) { state.euros += item.price * 0.897424392; @@ -92,7 +92,7 @@ var combineTotalPriceReducers = function(reducers) { reducers[key](state, item); return state; }, - {} + {} ); } }; diff --git a/_posts/zh_TW/2016-02-26-extract-unix-timestamp-easily.md b/_posts/zh_TW/2016-02-26-extract-unix-timestamp-easily.md new file mode 100644 index 00000000..1488a213 --- /dev/null +++ b/_posts/zh_TW/2016-02-26-extract-unix-timestamp-easily.md @@ -0,0 +1,45 @@ +--- +layout: post + +title: 在 JavaScript 簡單取得 unix timestamp +tip-number: 49 +tip-username: nmrony +tip-username-profile: https://github.com/nmrony +tip-tldr: 在 JavaScript 你可以簡單取得 unix timestamp + +categories: + - zh_TW +--- + +我們經常需要計算 unix 的 timestamp。有許多方式可以取得 timestamp。目前取得 unix timestamp 最簡單和快速的方式是: + +```js +const timestamp = Date.now(); +``` +or + +```js +const timestamp = new Date().getTime(); +``` + +如果要取得特定的 unix timestamp 傳送一個 `yyyy-mm--dd` 參數到 `Date` 的建構子。例如: + +```js +const timestamp = new Date('2012-06-08').getTime() +``` + +當你宣告一個 `Date` 物件,也可以加上 `+` 符號: + +```js +const timestamp = +new Date() +``` +或指定日期 + +```js +const timestamp = +new Date('2012-06-08') +``` +在執行時呼叫了 `Date` 物件的 `valueOf` 方法。`+` 運算子呼叫了 `toNumber()` 和回傳的值。更多細節的說明請參考以下的連結。 + +* [Date.prototype.valueOf](http://es5.github.io/#x15.9.5.8) +* [Unary + operator](http://es5.github.io/#x11.4.6) +* [toNumber()](http://es5.github.io/#x9.3) diff --git a/_sass/_highlights.scss b/_sass/_highlights.scss index 929ec6f9..1650aaec 100644 --- a/_sass/_highlights.scss +++ b/_sass/_highlights.scss @@ -1,15 +1,20 @@ +.highlighter-rouge { + max-width: none !important; + background-color: #F9F9F9; + border-top: 1px solid #ccc; + border-bottom: 1px solid #ccc; + margin: 20px auto !important; + padding: 20px 0; + + @media (max-width: 900px) { + margin: 0 10px; + padding: 10px 0; + } +} .highlight { - background-color: #F9F9F9; - padding: 20px 0; overflow: scroll; - border-top: 1px solid #ccc; - border-bottom: 1px solid #ccc; line-height: 1.2; - - @media (max-width: 900px) { - padding: 0 10px - } } code { diff --git a/style.scss b/style.scss index 64a15b8f..6abd7924 100644 --- a/style.scss +++ b/style.scss @@ -711,8 +711,6 @@ img { } .highlight { - max-width: none; - margin: 50px 0; overflow: hidden; @media (max-width: 900px) {