JavaScript
- 判断优化
if( falg ){someMethod()}
if( falg ){ someMethod()}
if( code === '202' || code === '203' || code === '204' ){someMethod()}
if( ['202','203','204'].includes(code) ){someMethod()}
- Array.prototype.slice.call(arguments)能将具有length属性的对象(key值为数字)转成数组。[]是Array的示例,所以可以直接使用[].slice()方法。
var obj = {0:'hello',1:'world',length:2};
console.log(Array.prototype.slice.call(obj,0));
var obj = {0:'hello',1:'world'};
console.log(Array.prototype.slice.call(obj,0));
- 手动实现缓存方法
const slice = Array.prototype.slice;
function memoize(fn) {
const cache = {};
return (...args) => {
const params = slice.call(args);
console.log(params);
if (cache[params]) {
console.log('cached');
return cache[params];
} else {
let result = fn(...args);
cache[params] = result;
console.log(`not cached`);
return result;
}
}
}
const makeFullName = (fName, lName) => `${fName} ${lName}`;
const reduceAdd = (numbers, startingValue = 0) => numbers.reduce((total, cur) => total + cur, startingValue);
const memoizedMakeFullName = memoize(makeFullName);
const memoizedReduceAdd = memoize(reduceAdd);
memoizedMakeFullName("Marko", "Polo");
memoizedMakeFullName("Marko", "Polo");
memoizedReduceAdd([1, 2, 3, 4, 5], 5);
memoizedReduceAdd([1, 2, 3, 4, 5], 5);