文章目录
- 1、含有多个条件的 if 语句
- 2、If … else 的缩写法
- 3、关于 null, undefined 的检查与指定默认赋值.
- 4、聚合运算符
- 5、为多个变量赋值
- 6、判断变量是否存在的缩写法
- 7、多条件下的与(&&)运算符
- 8、箭头函数
- 9、根据条件调用不同函数
- 10、比较结果的返回
- 11、Switch对应的缩写法
- 12、隐式返回缩写表达
- 13、十进制指数形式
- 14、函数参数默认值
- 15、扩展运算符的缩写表达
- 16、文本模板
- 17、字符串转成数字
- 18、解构赋值缩写法
- 19、Array.find缩写表达方式
- 20、查找条件缩写表达方式
- 21、按位非和indexOf缩写法
- 22、对象转换为对象数组
- 23、双位运算符缩写的表达方式
- 24、在数组中找到最大最小值
- 25、数学指数幂函数的简略表达方式
- 26、多次重复一个字符串
1、含有多个条件的 if 语句
可以在数组中存储多个值,也可以使用数据的includes方法。
//longhand
if (x === 'abc' || x === 'def' || x === 'ghi'){
//logic
}
//shorthand
if (['abc', 'def','ghi'].includes(x)){
//logic
}
2、If … else 的缩写法
当 if-else 条件下的逻辑比较简单时,可以使用三元条件运算符。
//longhand
let test: boolean;
if (x > 100){
test = true;
}else{
test = false;
}
//shorthand
let test = (x > 100) ? true : false;
//或者可以直接使用
let test = x > 100;
如果包含嵌套条件,也可以使用这种方法。
let x = 300,
test = (x > 100) ? 'greater than 100' : (x < 50) ? 'less than 50' : 'between 50 and 100';
console.log(test); // 'greater than 100'
当 if-else 过多是可以考虑 目录11 Switch对应的缩写法
。
3、关于 null, undefined 的检查与指定默认赋值.
当创建新的变量时,有时候需要检查引用变量的值是否为null或是undefined,js本身就有一种缩写法能实现这个功能。
//longhand
if (test !== null || test !== undefined){
let test1 = test;
}
//shorthand
let test = null,
test1 = test || '';
console.log(test1 );// 输出''
检查变量是null、undefined、0、false、NaN还是空string
//longhand
const isFalsey = (val) => {
if (
val === null ||
val === undefined ||
val === 0 ||
val === false ||
val === NaN ||
val === ''
) {
return true;
}
return false;
}
//shorthand
const isFalsey = (val) => !val;
4、聚合运算符
** ?? ** 是聚合运算符,如果左值为null或undefined,就返回右值。默认返回左值。
const test = null ?? 'default';
console.log(test); // 输出'default'
const test1 = 0 ?? 2;
console.log(test1 ); // 输出 0
5、为多个变量赋值
//longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//shorthand
let [test1, test2, test3] = [1, 2, 3]
6、判断变量是否存在的缩写法
在工作中常用的缩写表达方式之一,如今仍然值得被提起。
//longhand
if (test === true){} or if (test !== ''){} or if (test !== null){}
//shorthand
// it will check empty string, null and undefined too
if (test){}
注意:如果 test 有任何值,程序都会执行 if(test){} 内的逻辑,这种写法在判断 null 或 undefined 值时普遍使用。
7、多条件下的与(&&)运算符
如果我们只在变量为 true 的时候调用函数,那么我们就可以运用 && 运算符。
//longhand
if (test){
callMethod();
}
//shorthand
test && callMethod();
8、箭头函数
//longhand
function add(a, b){
return a + b;
}
//shorthand
const add = (a, b) => a + b;
更多实例如下
//longhand
function callMe(name){
console.log('Hello', name);
}
//shorthand
callMe = name => console.log('Hello', name);
9、根据条件调用不同函数
可以通过三元运算符实现如下功能
重要说明:函数的callsignature必须相同,否则会遇到错误。
//longhand
function test1(){
console.log('test1');
}
function test2(){
console.log('test2');
}
var test3 = 1;
if (test3 == 1){
test1();
}else{
test2();
}
//shorthand
(test3 === 1 ? test1 : test2)();
10、比较结果的返回
在return语句中,也可以使用比较的语句。
let test;
var data = checkReturn();
console.log(data);
function callMe(val){
console.log(val);
}
//longhand
function checkReturn(){
if(!(test === undefined)){
return test;
}else{
return callMe('test');
}
}
//shorthand
function checkReturn(){
return test || callMe('test');
}
11、Switch对应的缩写法
可以将条件保存在键值对中,并可以根据条件进行使用。
//longhand
switch(data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test3();
break;
}
//shorthand
var data = {
1: test1,
2: test2,
3: test3
};
data[somtheing] && data[something]();
//longhand
let str;
switch(data) {
case 1:
//todo
break;
case 2:
//todo
break;
case 3:
//todo
break;
}
//shorthand
const methods = new Map([
['1',()=>{//todo}],
['2',()=>{//todo}],
['3',()=>{//todo}],
['4',()=>{//todo}],
])
let action = methods.get(a);
action.call(this)
//longhand
let str;
switch(data) {
case 'r1':
str= 'test1';
break;
case 'r2':
str= 'test2';
break;
case 'r2':
str= 'test3';
break;
}
//shorthand
var data = {
r1: test1,
r2: test2,
r3: test3
};
return data[num] || '默认数据';
12、隐式返回缩写表达
使用箭头函数,可以直接得到函数运行结果,不需要再去写 return 语句。
//longhand
function calculate(diameter) {
return Math.PI * diameter;
}
//shorthand
calculate = diameter => (
Math.PI * diameter;
)
13、十进制指数形式
//longhand
for (var i = 0; i < 10000; i++) {...}
//shorthand
for (var i = 0; i < 1e4; i++) {...}
14、函数参数默认值
//longhand
function add(test1, test2) {
if (test1 === undefined)
test1 = 1;
if (test2 === undefined)
test2 = 2;
return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);
add();//输出3
15、扩展运算符的缩写表达
//longhand
//使用concat连接数组
const data = [1, 2, 3];
const test = [4, 5, 6].concat(data);
//shorthand
const data = [1, 2, 3];
const test = [4, 5, 6, ...data];
console.log(test);//输出[4, 5, 6, 1, 2, 3]
也可以使用延展操作符来克隆。
//longhand
//克隆数组
const test1 = [1, 2, 3];
const test2 = test1.slice();
//shorthand
//克隆数组
const test1 = [1, 2, 3];
const test2 = [...test1];
16、文本模板
//longhand
const welcome = 'Hi '+ test1 + ' ' + test2 + '.';
//shorthand
//与波浪号同键位,不需要按住shift -> ``
const welcome = `Hi ${test1} ${test2}`;
17、字符串转成数字
//longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
//shorthand
let test1 = +'123';
let test2 = +'12.3';
18、解构赋值缩写法
//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test3 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;
19、Array.find缩写表达方式
在对象数组中,通过对象属性来查找特定的对象。
const data = [{
type: 'test1',
name: 'abc'
},{
type: 'test2',
name: 'cde'
},{
type: 'test1',
name: 'fgh'
}
];
function findTest1(name){
for (let i = 0; i < data.length; ++i) {
if (data[i].type === 'test1' && data[i].name === name) {
return data[i];
}
}
}
//shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData);// { type: 'test1', name: 'fgh' }
20、查找条件缩写表达方式
根据不同的类型调用不同的方法
//longhand
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);
}
//shorthand
var type = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();
21、按位非和indexOf缩写法
//longhand
if (arr.indexOf(item) > -1) { // arr 存在 item
}
if (arr.indexOf(item) === -1) { // arr 不存在 item
}
//shorthand
if (~arr.indexOf(item)) { // arr 存在 item
}
if (!~arr.indexOf(item)) { // arr 不存在 item
}
按位操作符 ~
可以返回一个准确的值,除了-1。否定只需要 !~
。还可以通过 includes()
函数来代替。
if (arr.includes(item)) {
// 如果存在 item 则返回 true
}
22、对象转换为对象数组
Object.entries()
可以帮助我们将对象转换成对象数组。
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/**输出
*[ [ 'test1', 'abc' ],
*[ 'test2', 'cde' ],
*[ 'test3', 'efg' ]
*]
*/
Object.values()
是ES8中引入的一个新特性,它执行的功能与 Object.entries()
相似,但没有 key 值:
const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/**输出
*[ 'abc', 'cde' ]
*/
23、双位运算符缩写的表达方式
两个按位运算符方法仅适用于32位整数
//longhand
Math.floor(1.9) === 1 // true
//shorthand
~~1.9 === 1 // true
24、在数组中找到最大最小值
const arr = [1, 2, 3];
Math.max(...arr); // 3
Math.min(...arr); // 1
25、数学指数幂函数的简略表达方式
//longhand
Math.pow(2, 3); // 8
//shorthand
2**3 // 8
26、多次重复一个字符串
//longhand
let test = '';
for (let i = 0; i < 5; i++) {
test += 'test ';
}
console.log(str); // test test test test test
//shorthand
'test '.repeat(5);