小小技巧

115 阅读1分钟

生成26个英文字母

export function generateSingerAlpha() {
  var alphabets = ["-1"];
  var start = 'A'.charCodeAt(0);
  var last  = 'Z'.charCodeAt(0);
  for (var i = start; i <= last; ++i) {
    alphabets.push(String.fromCharCode(i));
  }

  alphabets.push("0");

  return alphabets;
}

展开语法

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

在函数调用时使用展开语法 等价于apply的方式

Math.max.apply(null, numArray);

等价于

通过使用最新的扩展语句spread operator,获得数组中的最大值变得更容易。

var arr = [1, 2, 3];
var max = Math.max(...arr);

剩余语法

剩余参数语法允许我们将一个不定数量的参数表示为一个数组。

剩余语法与展开语法是相反的:展开语法将数组展开为其中的各个元素,而剩余语法则是将多个元素收集起来并“凝聚”为单个元素

function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current;
  });
}

console.log(sum(1, 2, 3));
// expected output: 6

console.log(sum(1, 2, 3, 4));
// expected output: 10

位运算

请注意 位运算适用于 32 位整数,所以精度可能会丢失

用 "|" 取整

let num=1.5
num=num|0; // 1

用 ">>" 取半

let num=4;
num=num>>1; // 2

用 "<<" 加倍

let num=2;
num=num<<1; / / 4

用 "^" 两值交换

let a=1;
let b=2;

a^=b;
b^=a;
a^=b;
// a===2,b===1

用 "&" 判断奇数

let n=3;
let m=4;
n&1===1; // true 奇数
m&1===1; // false 偶数

用 "~" 判断项是否存在

let firstname="Ma";
let fullname="Jack Ma";
let isExist=!!~fullname.indexOf(firstname); // true

取整的快速写法(位运算) ~~

// prettier-ignore
~~ 2.7 === 2;
// prettier-ignore
~~ -2.7 === -2;

TS 中使用 typeof 关键字可以自动获取数据类型

const initialState = {
   username: '',
   mobile: '',
   isVip: false,
   addresses: [],
}

type IState = typeof initialState

class Comp extends Component<any, IState> {
   constructor(props) {
        super(props);
        this.state = {
            ...initialState
        };
    }
}

交换数组指定位置元素位置

// x , y是要交换元素的位置(index+1)
function arrIndexExchange(array, x, y){
    array.splice(x - 1, 1, ...array.splice(y - 1, 1, array[x - 1]));
    return array;
};
// [1 ,2, 3, 4] ===> [1, 2, 4, 3]

ES6 proxy 深度代理一个对象

function deepProxy(object, handler) {
    if (isComplexObject(object)) {
        addProxy(object, handler);
    }
    return new Proxy(object, handler);
}

function addProxy(obj, handler) {
    for (let i in obj) {
        if (typeof obj[i] === 'object') {
            if (isComplexObject(obj[i])) {
                addProxy(obj[i], handler);
            }
            obj[i] = new Proxy(obj[i], handler);
        }
    }
}

function isComplexObject(object) {
    if (typeof object !== 'object') {
        return false;
    } else {
        for (let prop in object) {
            if (typeof object[prop] == 'object') {
                return true;
            }
        }
    }
    return false;
}

let person = {
    txt: 123,
    name: 'tnt',
    age: 26,
    status: {
        money: 'less',
        fav: [1, 2, 3]
    }
};
let proxyObj = deepProxy(person, {
    get(target, key, receiver) {
        console.log(`get--${target}--${key}`);
        return Reflect.get(target, key);
    },
    set(target, key, value, receiver) {
        console.log(`set--${target}--${key}-${value}`);
        return Reflect.set(target, key, value);
    }
});
proxyObj.status.test = 13;
proxyObj.status.fav.push('33');