平時使用的字符串應該是primitive類型,應該是not an object and has no methodsjavascript
const str = 'hello'; console.log(str.charAt(0)); // output: h Object.prototype.toString.call(str) // output: [object String]
N次循環技巧java
for(let i = 0; i < 5; i++) { // ... } Array.apply(null, Array(5)).forEach(() => { // ... }); _.times(5, () => { // ... };
深層次查找屬性git
const ownerArr = [{ "owner": "Colin", "pets": [{"name":"dog1"}, {"name": "dog2"}] }, { "owner": "John", "pets": [{"name":"dog3"}, {"name": "dog4"}] }]; ownerArr.map(owner => { return owner.pets[0].name; }); _.map(ownerArr, 'pets[0].name');
數組獨立es6
Array.apply(null, Array(6)).map( (item, index) => { return "ball_" + index; }); _.times(6, _.uniqueId.bind(null, 'ball_')); _.times(6, _.partial(_.uniqueId, 'ball_')); // output: [ball_0, ball_1, ball_2, ball_3, ball_4, ball_5]
對象擴展(能夠直接用Object.assgin(), 底層同樣的實現)github
Object.prototype.extend = obj => { for (let i in obj) { if (obj.hasOwnProperty(i)) { this[i] = obj[i]; } } }; const objA = {"name": "colin", "car": "suzuki"}; const objB = {"name": "james", "age": 17}; objA.extend(objB); console.log(objA); // {"name": "james", "age": 17, "car": "suzuki"}; _.assign(objA, objB); // {"name": "james", "age": 17, "car": "suzuki"}; // ES6 Objetct.assign({}, objA, objB); // {"name": "james", "age": 17, "car": "suzuki"}; //_.assign 是淺拷貝,因此會覆蓋name
補充做用域:數組
const test = '1'; testOne() { return testTwo{ cosole.log(test); }; const test = '2'; } testOne()(); // output: undefined const test = '1'; testOne() { return testTwo{ console.log(test); }; test = '2'; } // output: 1;
由於從新定義了const,他在搜索做用域時候,會自上到下搜索聲明的變量,若是沒有聲明,查找纔會進去下一層,此處輸出undefined,由於在testOne()裏面const以前就使用了test,因此就輸出了undefined,而在第二個例子裏面沒有聲明test,因此他就跳轉出去,去下一層尋找test,即輸出爲1app
做用域提高this
const a = 1; b(){ const a = b = 2; } console.log(a, b); // 拋出異常,由於b沒有定義 b(); console.log(a, b); //output: 1,2; // const a = b = 2 等價於 在全局聲明const b = 2; 內部聲明const a = b;由於=運算符是重右像左運算的