平时使用的字符串应该是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;由于=运算符是重右像左运算的