Array
所有都以代码实现,talk is cheap, show me the code:
// 创建
var arr = [2, 3, 4, 5, 'string', {'color': 'red'}, [1, 2, 3]];
var arr = new Array(args); // see the API, not recommanded way
// 访问
arr[2]; // Notice: JS不存在越界问题,如果越界,放回 undefined
// 属性
a.length;
a.length = 0; // clear the array
// 方法, for the detail please see the API
console.log(Array.prototype);
var fn = Array.prototype;
fn.push();
fn.pop();
fn.shift();
fn.unshift();
fn.splice();
fn.concat();
// 推荐用于拷贝数组
fn.slice();
fn.indexOf();
fn.lastIndexOf();
fn.sort(fun); // sort with comparison function
fn.reverse();
fn.join();
fn.toString();
fn.toArray();
fn.reduce(pre, cur, index, arr);
fn.reduceRight(pre, cur, index, arr);
fn.forEach(iterator);
fn.map(map);
fn.filter(filter);
for (var i = 0; i < arr.length; i += 1) // do something
// es6 features
Array.from(document.querySelectorAll('*')) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
[0, 0, 0].fill(7, 1) // [0,7,7]
[1, 2, 3].find(x => x == 3) // 3
[1, 2, 3].findIndex(x => x == 2) // 1
[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["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.
var buffer = new ArrayBuffer(8);
var view = new Int32Array(buffer);
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()
andObject.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 keysmap.values();
iterate valuesmap.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;
- The
add()
,has()
, anddelete()
methods throw an error when passed a non-object. - Weaksets are not iterables and therefore cannot be used in a
for-of
loop. - Weaksets do not expose any iterators (such as
keys()
andvalues()
), 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.