1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| 1. swap variable value: let x = 1; let y = 2;
[x, y] = [y, x];
2. return multiple values: return array: function example() { return [1, 2, 3]; } let [a, b, c] = example(); return object: function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example();
3. define function parameters: parameters 有順序性 -> array ----------------------------- function f([x, y, z]) { ... } f([1, 2, 3]); parameters 無順序性 -> object ----------------------------- function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});
4. fetch json data: let jsonData = { id: 42, status: "OK", data: [867, 5309] };
let { id, status, data: number } = jsonData;
console.log(id, status, number); // 42, "OK", [867, 5309]
5. function default parameters: jQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, global = true, // ... more config } = {}) { // ... do stuff };
6. for loop -> Map 任何有實作Iterator interface的結構,都可以用for const map = new Map(); map.set('first', 'hello'); map.set('second', 'world');
for (let [key, value] of map) { console.log(key + " is " + value); } // first is hello // second is world
get key: for (let [key] of map) { // ... }
get value: for (let [,value] of map) { // ... }
7. 指定import module const { SourceMapConsumer, SourceNode } = require("source-map");
|