— Programming — 1 min read
Speaking Javascript - Dr. Axel Rauschmayer
1// Array are maps not tuples2// 1. Array has hole3const arr = []4arr[1] = "1" // arr => [, "1"]5// 2. Array has props6arr.foo = 1237
8
9// ---------------------10// Array indices11// Indices that are out of range are treated as property key12arr[-1] = 'a';13arr[4294967296] = 'b';14// arr => []15// arr['-1'] => 'a'16// arr['4294967296'] => 'b'17
18// ---------------------19// Delete array elements will create hole20const arr = ['a', 'b']21delete arr[1]22// arr => ['a', ]23
24// So should use splice(Destructive) to not create hole25arr.splice(1,1)26// arr => ['a']27
28// ---------------------29// Methods that check/skip holes30// Check31.join, sort32
33// Skip34.forEach, every/some, map, filter, for in35// Note: `in` operator will loop through property keys and indices36const arr = [1];37arr.foo = 'bar';38for (const key in arr) {39 console.log(key); // 1, foo40}41
42// ---------------------43// Array prototype methods44
45// Add/Remove elements(Destructive)46arr.shift/unshift/pop/push/splice()47// Sorting/Reversing elements(Destructive)48arr.reverse/sort()49
50// Concatenating/Slicing/Joining elements(NonDestructive)51arr.concat/slice/join()52// Search(NonDestructive)53arr.indexOf/lastIndexOf()54// Iteration(NonDestructive)55arr.forEach/every/some()56
57// Transformation(NonDestructive)58arr.map/filter()59// Reduction(NonDestructive)60arr.reduce()
1// Normal for2for (let i = 0; i < arr.length; i++) {3 const element = arr[i];4}5
6// For-in: loop through any object7for (let key in arr) {8}9
10// For-of: loop through only iterable object11for (let key of Object.keys(o)) {12}
1// Useful functions2s.split(",");3s.slice((start = 1), (end = 2));4s.trim();5s.toLowerCase();6s.toUpperCase();7s.indexOf(",");8s.lastIndexOf(",");9s.replace("a", "b");
1// Check NaN2Number.isNaN(x)3
4// Converting5Number(undefined) => NaN6Number(null) => 07Number(NaN) => NaN8Number(false) => 09Number('3.14') => 3.1410Number(o: Object) => Call ToPrimitive
1// Converting2Boolean(null, undefined, NaN, 0, ""); // => false3Boolean({}); // => true for any object
1document.getElementById("foo"); // null
1// When converting variable to number20 / 0; // NaN3Infinity - Infinity; // NaN4Math.sqrt(-1); // NaN5parseInt("foo"); // NaN
1// Uninit variable2let a; // undefined3
4// Missing params5function foo(a, b) {6 console.log(b); // undefined7}8
9// Object access nonexistence prop10const o = {};11console.log(o.a); // undefined12
13// Function with no return14function foo() {}15console.log(foo()); // undefined