Javascrpt three 简写与优化

158 阅读2分钟

函数

1. switch

我们可以将条件保存在键值对象中,并可以根基条件使用。

// long
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // And so on...
}

// short
var data = {
  1: test1,
  2: test2,
  3: test
};

data[something] && data[something]();

2. 多个条件判断

// long
if( x === 'a' || x === 'b' || x === 'c' || x === 'd'){
  // logic
}

// short
if(['a', 'b', 'c', 'd'].includes(x)){
  // logic
}

// long
if (type === 'test1') {
  test1();
}
else if (type === 'test2') {
  test2();
}
else if (type === 'test3') {
  test3();
}
else if (type === 'test4') {
  test4();
} else {
  throw new Error('Invalid value ' + type);
}

// short
const types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};
 
let func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();

3. 参数必传校验

// long
function hello(obj){
  let {name, age} = obj
  if(!name){
    console.warn('name is null, pls check!')
    return ''
  }
  if(!age){
    console.warn('age is null, pls check!')
    return ''
  }
  return `${name}: ${age}`
}

// short
function hello(obj){
  let {name = required('name'), age = required('age')} = obj
  return `${name}: ${age}`
}

function required(key){
  console.warn(`${key} is null, pls check!')
}

Object

1.Object.entries()将对象转换为对象数组

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** ouput

[ [ 'test1', 'abc' ],
  [ 'test2', 'cde' ],
  [ 'test3', 'efg' ]
]

**/

2.Object.values()

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:

[ 'abc', 'cde']

**/

字符串

1. 重复字符串多次

//long 
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 
console.log(str); // test test test test test 

//short 
'test '.repeat(5);

2. 字符串=>数字

//Long
let test1 = parseInt('123'); 
let test2 = parseFloat('12.3'); 

//Short
let test1 = +'123'; 
let test2 = +'12.3';

数组

1.数组最大最小值

const arr = [1, 2, 3]; 
Math.max(…arr); // 3
Math.min(…arr); // 1

2. 索引查找

//long
if(arr.indexOf(item) > -1) { // item found 
}
if(arr.indexOf(item) === -1) { // item not found
}

//short
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}

按位运算符将返回非-1的真实值。取反就像做一样简单。另外,我们也可以使用include()函数:

if (arr.includes(item)) { 
// true if the item found
}

3. 扩展运算符

//long
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);


//short
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]

克隆

//long
const test1 = [1, 2, 3];
const test2 = test1.slice()

//short
const test1 = [1, 2, 3];
const test2 = [...test1];