多条件If
在数组中存储多个值,使用数据的includes方法。
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') { //logic}//shorthandif (['abc', 'def', 'ghi', 'jkl'].includes(x)) { //logic}
检查 null/undefined/空
当我们创建新的变量时,有时候需要检查我们引用变量的值是否为null
或是undefined
,js本身就有一种缩写法能实现这个功能
// Longhandif (test1 !== null || test1 !== undefined || test1 !== '') { let test2 = test1;}// Shorthandlet test2 = test1 || '';
Nullish合并操作符??
如果左边为null或undefined
,则返回右边值。否则,返回左边的值。
const test= null ?? 'default';console.log(test);// 将会输出: "default"const test1 = 0 ?? 2;console.log(test1);// 将会输出: 0
给多个变量赋值
// Longhandlet test1 = 1;let test2 = 2;let test3 = 3;// Longhand-let test1 = 1, test2 = 2, test3 = 3;// Shorthandlet [test1, test2, test3] = [1, 2, 3];
判断是否false/null/空/undefined
这是我们工作中常用的缩写表达方式之一,如今它仍然值得被提起。
// Longhandif (test1 === true) or if (test1 !== "") or if (test1 !== null) or if (!(test1 === undefined))// Shorthandif (test1)
通过与运算符(&&
)调用函数
如果我们只在变量为true的时候调用函数,那么我们就可以运用&&
运算符。
Tips: 和 &&
原理一样,通过 ||
或者! &&
可以做到变量为false时调用
//Longhandif (test1) { callMethod();}//Shorthandtest1 && callMethod();
比较结果的返回
// Longhandlet test;function checkReturn() { if (!(test === undefined)) { return test; } else { return callMe('test'); }}let data = checkReturn();console.log(data); //output testfunction callMe(val) { console.log(val);}// Shorthandfunction checkReturn() { return test || callMe('test');}
利用三元运算符调用函数
function test1() { console.log('test1');};function test2() { console.log('test2');};// Longhandlet test3 = 1;if (test3 === 1) { test1();} else { test2();}// Shorthand(test3 === 1? test1:test2)();
switch缩写
// Longhandswitch (data) { case 1: test1(); break; case 2: test2(); break; case 3: test(); break;}
// Shorthandlet data = { 1: test1, 2: test2, 3: test};//进行检查 调用data[1] && data[1]();
十进制指数形式
// Longhandfor (let i = 0; i < 10000; i++) { ... }
// Shorthandfor (let i = 0; i < 1e4; i++) { ... }
默认参数值
如同C#
// Longhandfunction add(test1, test2) { if (test1 === undefined) test1 = 1; if (test2 === undefined) test2 = 2; return test1 + test2;}// Shorthandfunction add(test1 = 1, test2 = 2) { return test1 + test2;}// 使用lambda表达式add = (test1 = 1, test2 = 2) => (test1 + test2);
扩展运算符
拼接数组
// Longhandconst data = [1, 2, 3];const test = [4 ,5 , 6].concat(data);// Shorthandconst data = [1, 2, 3];const test = [4 ,5 , 6, ...data];
复制数组
// Longhandconst test1 = [1, 2, 3];const test2 = test1.slice()// Shorthandconst test1 = [1, 2, 3];const test2 = [...test1];
文本模板
如同C#,C#中使用$"{变量} {变量}"
的,js中使用`${变量} ${变量}`
// Longhandconst welcome = 'Hi ' + test1 + ' ' + test2 + '.'// Shorthandconst welcome = `Hi ${test1} ${test2}`;
当我们在处理代码中的多行字符串问题时,同样可以使用文本模板
它只会在读取到`
时才结束。当然,内容中可以使用\`
来转义
//longhandconst data = 'abc abc abc abc abc abc\n\t' + 'test test,test test test test\n\t'//shorthandconst data = `abc abc abc abc abc abctest test,test test test test`
ES6对象赋值缩写
属性缩写(同名的话直接取变量名作为键了)
let test1 = 'a';let test2 = 'b';// Longhandlet obj = {test1: test1, test2: test2};// Shorthandlet obj = {test1, test2};
方法缩写
// Longhandlet obj = { test:function (params) { //... }}// Shorthandlet obj = { test(params) { //... }}
字符串转成数字
// Longhandlet test1 = parseInt('123');let test2 = parseFloat('12.3');// Shorthandlet test1 = +'123';let test2 = +'12.3';
解构赋值缩写法
Destructuring Assignment Shorthand
// Longhandconst test1 = this.data.test1;const test2 = this.data.test2;const test2 = this.data.test3;// Shorthandconst { test1, test2, test3 } = this.data;
Array.find
当我们有一个数组,并且我们需要根据对象的属性来查找特定的对象时,这个方法非常有用。
const data = [ { type: 'test1', name: 'abc' }, { type: 'test2', name: 'cde' }, { type: 'test1', name: 'fgh' },]// Longhandfunction find(type,name) { for (let i = 0; i < data.length; ++i) { if (data[i].type === type && data[i].name === name) { return data[i]; } }}let filteredData = find('test1','fgh')//Shorthandlet filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
根据类型执行不同方法
// Longhand if (type === 'string') { test1(); } else if (type === 'number') { test2(); } else if (type === 'boolean') { test3(); } else { throw new Error('Invalid value ' + type); } // Shorthand let types = { 'string': test1, 'number': test2, 'boolean': test3, };
let func = types[type]; (!func) && throw new Error('Invalid value ' + type); func();
按位非和indexOf缩写法
// Longhandif(arr.indexOf(item) > -1) { // 存在}if(arr.indexOf(item) === -1) { // 不存在}// Shorthandif(~arr.indexOf(item)) { // 存在}if(!~arr.indexOf(item)) { // 不存在}
除了-1以外使用bitwise(~)
操作符都可以返回true
。我们也可以用includes()
函数来替代它。
if (arr.includes(item)) {}
Object.keys()和Object.values()
没什么好说的,就是取键和值
const data = { test1: 'abc', test2: 'cde' };const arr1 = Object.keys(data); //[ 'test1' , 'test2']const arr2 = Object.values(data); //[ 'abc', 'cde']
Object.entries()
对象转数组 MDN上的详解
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };const arr = Object.entries(data);
/** 输出[ [ 'test1', 'abc' ], [ 'test2', 'cde' ], [ 'test3', 'efg' ]]**/
遍历时候就可以使用
for (const [key, value] of Object.entries(data)) { console.log(`${key}: ${value}`);}
双按位运算符
(仅适用于32位整数)
// LonghandMath.floor(1.9) === 1 // true// Shorthand~~1.9 === 1 // true
多次重复一个字符串 .repeat()
做实体类转换器的时候用到过,非常实用!
// Longhandlet test = '';for(let i = 0; i < 5; i ++) { test += 'test ';}console.log(str); // test test test test test// Shorthand'test '.repeat(5);
获取数组中的最大最小值
const arr = [1, 2, 3];Math.max(…arr); // 3Math.min(…arr); // 1
从字符串中获取字符
let str = 'abc';// Longhandstr.charAt(2);// Shorthandstr[2];
两者的区别
使用string[index]
的方式,对于超出字符index范围的,会返回undefined
而使用charAt(index)的方式,对于超出范围的会返回一个空的字符串。
兼容性问题:
string[index]
的方式在 IE6~8 下也会返回undefined
, 也就是 IE6~8不兼容此方法 。
指数幂函数的简略表达方式
// LonghandMath.pow(2,3); // 8// Shorthand2**3 // 8
评论