Array

所有都以代码实现,talk is cheap, show me the code:

  1. // 创建
  2. var arr = [2, 3, 4, 5, 'string', {'color': 'red'}, [1, 2, 3]];
  3. var arr = new Array(args); // see the API, not recommanded way
  4. // 访问
  5. arr[2]; // Notice: JS不存在越界问题,如果越界,放回 undefined
  6. // 属性
  7. a.length;
  8. a.length = 0; // clear the array
  9. // 方法, for the detail please see the API
  10. console.log(Array.prototype);
  11. var fn = Array.prototype;
  12. fn.push();
  13. fn.pop();
  14. fn.shift();
  15. fn.unshift();
  16. fn.splice();
  17. fn.concat();
  18. // 推荐用于拷贝数组
  19. fn.slice();
  20. fn.indexOf();
  21. fn.lastIndexOf();
  22. fn.sort(fun); // sort with comparison function
  23. fn.reverse();
  24. fn.join();
  25. fn.toString();
  26. fn.toArray();
  27. fn.reduce(pre, cur, index, arr);
  28. fn.reduceRight(pre, cur, index, arr);
  29. fn.forEach(iterator);
  30. fn.map(map);
  31. fn.filter(filter);
  32. for (var i = 0; i < arr.length; i += 1) // do something
  33. // es6 features
  34. Array.from(document.querySelectorAll('*')) // Returns a real Array
  35. Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
  36. [0, 0, 0].fill(7, 1) // [0,7,7]
  37. [1, 2, 3].find(x => x == 3) // 3
  38. [1, 2, 3].findIndex(x => x == 2) // 1
  39. [1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]
  40. ["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
  41. ["a", "b", "c"].keys() // iterator 0, 1, 2
  42. ["a", "b", "c"].values() // iterator "a", "b", "c"

Notice:

  • JavaScript 数组和 C系类以及 Java 不同,是 动态数组 ,支持多类型,而且支持 稀疏数组
  • 数组在 JS 之中,本身是对象,可以用对象的方法来处理数组。
  • 在类数组对象上使用通用数组方法,如:[].forEach.call(likearry, func);
  • 数组迭代优先使用 for, while 而非 for-in 循环

ArrayBuffer & Typed Array

ArrayBuffer gives you a chunk of contiguous memory chunk and let you do whatever you want with it. However, dealing directly with memory is very low level and more complicated. So we have Views to deal with ArrayBuffer. There are already some views available and more can be added in future.

Typed arrays are performant and efficient. It was introduced after the request from WebGL people, as they were facing immense performance issues without a way to handle binary data efficiently. You can also share the memory using SharedArrayBuffer across multiple web-workers to get a performance boost.

Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array etc are typed array views, who are in native byte order.

  1. var buffer = new ArrayBuffer(8);
  2. var view = new Int32Array(buffer);
  3. view[0] = 100;

ES6 Object

The object category:

  • Ordinary objects are objects that have all of the default internal behaviors for objects in JavaScript.
  • Exotic objects are objects whose internal behavior is different than the default in some way.
  • Standard objects are objects defined by ECMAScript 6, such as Array, Date, etc. Standard objects may be ordinary or exotic.
  • Built-in objects are objects that are present in a JavaScript execution environment when a script begins to execute. All standard objects are built-in objects.

The New Features:

  • Object Literal Expression

    • Property Initializer Shorthand
    • Method Initializer Shorthand
    • Computed Property Name
function createPerson(name, age) {
   return { name, age };
}

var person = {
    name: "Nicholas",
    sayName() { console.log(this.name);}
};

var suffix = " name";
var person = {
    handler, // equal: handler : handler,
    ["first" + suffix]: "Nicholas",
    ["last" + suffix]: "Zakas"
};
console.log(person["first name"]);      // "Nicholas"
console.log(person["last name"]);       // "Zakas"
  • Mixin with Object.assign()
var receiver = {};
Object.assign(receiver, { type: "js", name: "file.js"}, { type: "css" });
console.log(receiver.type);     // "css"
console.log(receiver.name);     // "file.js"
  • Handle Prototype

    • Object.getPrototypeOf() and Object.setPrototypeOf()
    • __proto__ support
  • Super Reference
let friend = {
    __proto__: person,
    getGreeting() {
        // same as Object.getPrototypeOf(this).getGreeting.call(this)
        // or this.__proto__.getGreeting.call(this)
        return super.getGreeting() + ", hi!";
    }
};

ES6 Collections

Sets

A set is in an ordered list of values that cannot contain duplicates.

var items = new Set();
items.add();
items.size();
items.has();
items.delete();

for (let i in items) console.log(i);
var arr = Array.from(items);

Maps

The basic idea is to map a value to a unique key in such a way that you can retrieve that value at any point in time by using the key.

The ECMAScript 6 Map type is an ordered list of key-value pairs where both the key and the value can be of any type.

var map = new Map();
var map = new Map([ ["name", "Nicholas"], ["title", "Author"]]);

map.set("name", "Nicholas");
map.set(document.getElementById("my-div"), { flagged: false });
map.get();
map.has();
map.size;

The easiest way to iterate the items is to use a for-of loop:

  • map.keys(); iterate keys
  • map.values(); iterate values
  • map.entries(); iterate keys and values
for (let key of map.keys()) {
    console.log("Key: %s", key);
}
for (let value of map.values()) {
    console.log("Value: %s", value);
}
for (let item of map.entries()) {
    console.log("Key: %s, Value: %s", item[0], item[1]);
}
// same as using map.entries()
for (let item of map) {
    console.log("Key: %s, Value: %s", item[0], item[1]);
}

map.forEach(function(value, key, map)) {
    console.log("Key: %s, Value: %s", key, value);
});

Weaksets

Weaksets are a type of set that only stores object references, and as such, also cannot store duplicates. The key difference is that weaksets hold only a weak reference to each object, which means the reference stored in the weakset will not prevent garbage collection if it is the only remaining reference.

var set = new WeakSet();
set.add(obj);
set.delete(obj);
set.has(obj);

// remove the last strong reference to obj, also removes from weakset
obj = null;
  1. The add(), has(), and delete() methods throw an error when passed a non-object.
  2. Weaksets are not iterables and therefore cannot be used in a for-of loop.
  3. Weaksets do not expose any iterators (such as keys() and values()), so there is no way to programmatically determine the contents of a weakset.

Weekmaps

Weakmaps are similar to regular maps in that they map a value to a unique key. That key can later be used to retrieve the value it identifies. Weakmaps are different because the key must be an object and cannot be a primitive value.

A weakmap holds only a weak reference to a key in the same way weaksets hold a weak reference to a value. When the object is destroyed by the garbage collector, the weakmap automatically removes the key-value pair identified by that object.

var map = new WeakMap(),
    element = document.querySelector(".element");
map.set(element, "Original");
// later
var value = map.get(element);
console.log(value);             // "Original"
// later still - remove reference
element.parentNode.removeChild(element);
element = null;
value = map.get(element);
console.log(value);             // undefined

The ability to free up memory related to these objects is useful for JavaScript libraries that wrap DOM elements with custom objects such as jQuery.

Weakmaps are limited in that they aren’t enumerable and you can’t keep track of how many items are contained within. There also isn’t a way to retrieve a list of all keys.