JavaScript中if语句优化和部分语法糖小技巧推荐(Tips for if statement optimization and some syntax sugar in JavaScript)

前言

在前端日常开发过程中,if else判断语句使用的次数应该是比较频繁的了,一些较为复杂的场景,可能会用到很多判断,在某个代码块使用很多if else时,代码会显得较为冗余,阅读起来不够清晰。
除了if else,在开发过程中,还经常使用 逻辑运算符 && || 以及三木运算符? : 等。

  • 在前端日常开发过程中,if else判断语句使用的次数应该是比较频繁的了,一些较为复杂的场景,可能会用到很多判断,在某个代码块使用很多if else时,代码会显得较为冗余,阅读起来不够清晰。
  • 除了if else,在开发过程中,还经常使用 逻辑运算符 && || 以及三木运算符? : 等。

if else 基本使用

let name = "zhangsan";
if (name === "zhangsan") {
	console.log("zhangsan"); // zhangsan
} else {
	console.log("lisi");
}

简化if判断和优化代码

单行if else

if (name === "zhangsan") console.log("zhangsan");
else console.log("lisi");
		

使用&& || 优化


let userInfo = {
	name: "zhangsan",
};
if (userInfo.name === "zhangsan") {
	console.log("zhangsan");
}
if (!userInfo.age) {
	// userInfo.age--> false age属性不存在
	console.log("年龄属性不存在");
}
userInfo.name === "zhangsan" && console.log("zhangsan");
userInfo.age || console.log("年龄属性不存在"); // 年龄属性不存在

使用三目运算符优化

let name = "zhangsan";
name === "zhangsan" ? console.log("zhangsan") : console.log("lisi");

合并if


let userObj = { name: "zhangsan", children: { name: "lisi" } };
if (userObj.children) {
  if (userObj.children.name == "lisi") {
    console.log(userObj.children.name);
  }
}
if (userObj.children && userObj.children.name == "lisi")
  console.log(userObj.children.name);

使用includes 或者indexof


let age = "22";
if (age == "22" || age == "24" || age == "25") {
  console.log(age);
}
let ageArray = ["22", "24", "25"];
if (ageArray.includes(age)) {
  console.log(age);
}
if (ageArray.indexOf(age) > -1) {
  console.log(age);
}

使用switch流程 优化 多个if else

let val = "lisi";
switch (val) {
  case "zhangsan":
    console.log(val);
    break;
  case "lisi":
    console.log(val);
    break;
  case "xiaoming":
    console.log(val);
    break;
  case "xiaowang":
    console.log(val);
    break;
  default:
    console.log(val);
}

使用对象 key-value 优化多条if语句

let userArray = [
  { name: "zhangsan" },
  { name: "lisi" },
  { name: "xiaoming" },
  { name: "xiaowang" },
];

// 多重if else
if (userArray.name === "zhangsan") {
  console.log(userArray.name);
} else if (userArray.name === "lisi") {
  console.log(userArray.name);
} else if (userArray.name === "xiaoming") {
  console.log(userArray.name);
} else if (userArray.name === "xiaowang") {
  console.log(userArray.name);
} else {
  console.log("其他用户");
}

function getUser(username) {
  return userArray.filter((item) => item.name == username)[0];
}
console.log(getUser("zhangsan"));

使用map

let filterUser = function (username) {
  return `名字是${username}`;
};
let userMap = new Map([
  ["zhangsan", filterUser("zhangsan")],
  ["lisi", filterUser("lisi")],
  ["xiaoming", filterUser("xiaoming")],
  ["xiaowang", filterUser("xiaowang")],
]);
console.log(userMap.get("zhangsan"));   // 名字是zhangsan

推荐一些常用的JavaScript语法糖

箭头函数


/**
 * 箭头函数
 *
 * */
function userInfo(name, age) {
  return `名字是:${name},年龄是:${age}`;
}
let userInfo = (name, age) => `名字是:${name},年龄是:${age}`;
console.log(userInfo("zhangsan", "23"));

三目运算符处理函数

function log1() {
  console.log(1);
}
function log2() {
  console.log(2);
}
let num = 2;
if (num === 1) {
  log1();
} else {
  log2();
}
num === 1 ? log1() : log2();

函数默认参数处理

let getUser = (name = "zhangsan", age = 23) =>
      `名字是:${name},年龄是:${age}`;

console.log("默认参数", getUser());
console.log("传参", getUser("lisi", 29));

数据类型转换

let num1 = +"123";
console.log(num1);

Null、Undefined 布尔值等特殊值处理,使用||结合!

/**
 *
 * Null、Undefined 布尔值等特殊值处理,使用||结合!
 *
 * */
let name1 = undefined;
let name2 = null;
let name3 = true;
let name4 = false;
let name5 = "lisi";
console.log(name1 || "其他人"); // 其他人
console.log(name2 || "其他人"); // 其他人
console.log(name3 || "其他人"); // true
console.log(!name3 || "其他人"); // 其他人
console.log(name4 || "其他人"); // 其他人
console.log(name5 || "其他人"); // lisi
console.log(!name5 || "其他人"); // 其他人

链判断运算符

?.运算符在运算过程中,会首先从左到右执行,左侧的对象是否为null或undefined。如果是的,就不再往右边执行运算,而是返回undefined

?.运算符在运算过程中,会首先从左到右执行,左侧的对象是否为null或undefined。如果是的,就不再往右边执行运算,而是返回undefined

更多链判断运算符请参考

链判断运算符

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining


let user = {
  name: "zhangsan",
  children: { name: "lisi", children: { name: "xiaoming" } },
};
let name1 = user?.name;
let name2 = user?.children?.name;
let name3 = user?.children?.children?.name;
console.log(name1);
console.log(name2);
console.log(name3);

空值合并操作符 ??

概念

空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。
如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,” 或 0)时。

  • 空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
  • 与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。
  • 如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,” 或 0)时。

const foo = null ?? "default string";
const test = undefined ?? "default string";
const test1 = 123 ?? "default string";
console.log(test); // "default string"
console.log(foo); // "default string"
console.log(test1); // 123
const baz = 0 ?? 42;
console.log(baz); // 0
const str = "" ?? 42;
const str1 = "" || 42;
console.log(str); // ""
console.log(str1); // 42

小结

  • 以上就是对于if代码优化的一些建议,if else 在使用过程中,有时候会相对繁琐一些,但是也是较为直接的判断语句
  • 是否优化if语句,还是要根据具体的业务场景,具体去做,需要个人进行判断
  • JavaScript的语法糖在日常开发过程中,可以省去一些繁琐的判断或者说语义化
  • ES6或者更高版本的ECMA语法更新了不少,对于一些语法的扩展,在开发过程中还是提供了不少帮助。

源码地址

  • 码云 https://gitee.com/lewyon/vue-note

码云 https://gitee.com/lewyon/vue-note

  • githup https://github.com/akari16/vue-note

githup https://github.com/akari16/vue-note

文章博客地址:JavaScript中if语句优化和部分语法糖小技巧推荐

欢迎关注公众号:程序员布欧,不定期更新一些前端入门文章

创作不易,转载请注明出处和作者。

————————

preface

In the daily development process of the front end, if else judgment statements should be used more frequently. In some more complex scenarios, a lot of judgment may be used. When a code block uses a lot of if else, the code will appear redundant and not clear enough to read.
In addition to if else, the logical operator & amp; is often used in the development process& amp; || And Miki operator?: Wait.

  • In the daily development process of the front end, if else judgment statements should be used more frequently. In some more complex scenarios, a lot of judgment may be used. When a code block uses a lot of if else, the code will appear redundant and not clear enough to read.
  • In addition to if else, logical operators & & 𞓜 and Mitsuki operator?, are often used in the development process: Wait.

if else 基本使用

let name = "zhangsan";
if (name === "zhangsan") {
	console.log("zhangsan"); // zhangsan
} else {
	console.log("lisi");
}

Simplify if judgment and optimize code

单行if else

if (name === "zhangsan") console.log("zhangsan");
else console.log("lisi");
		

Use & & | optimization


let userInfo = {
	name: "zhangsan",
};
if (userInfo.name === "zhangsan") {
	console.log("zhangsan");
}
if (!userInfo.age) {
	// userInfo.age--> false age属性不存在
	console.log("年龄属性不存在");
}
userInfo.name === "zhangsan" && console.log("zhangsan");
userInfo.age || console.log("年龄属性不存在"); // 年龄属性不存在

Optimize with ternary operators

let name = "zhangsan";
name === "zhangsan" ? console.log("zhangsan") : console.log("lisi");

Merge if


let userObj = { name: "zhangsan", children: { name: "lisi" } };
if (userObj.children) {
  if (userObj.children.name == "lisi") {
    console.log(userObj.children.name);
  }
}
if (userObj.children && userObj.children.name == "lisi")
  console.log(userObj.children.name);

使用includes 或者indexof


let age = "22";
if (age == "22" || age == "24" || age == "25") {
  console.log(age);
}
let ageArray = ["22", "24", "25"];
if (ageArray.includes(age)) {
  console.log(age);
}
if (ageArray.indexOf(age) > -1) {
  console.log(age);
}

使用switch流程 优化 多个if else

let val = "lisi";
switch (val) {
  case "zhangsan":
    console.log(val);
    break;
  case "lisi":
    console.log(val);
    break;
  case "xiaoming":
    console.log(val);
    break;
  case "xiaowang":
    console.log(val);
    break;
  default:
    console.log(val);
}

Optimize multiple if statements with object key value

let userArray = [
  { name: "zhangsan" },
  { name: "lisi" },
  { name: "xiaoming" },
  { name: "xiaowang" },
];

// 多重if else
if (userArray.name === "zhangsan") {
  console.log(userArray.name);
} else if (userArray.name === "lisi") {
  console.log(userArray.name);
} else if (userArray.name === "xiaoming") {
  console.log(userArray.name);
} else if (userArray.name === "xiaowang") {
  console.log(userArray.name);
} else {
  console.log("其他用户");
}

function getUser(username) {
  return userArray.filter((item) => item.name == username)[0];
}
console.log(getUser("zhangsan"));

使用map

let filterUser = function (username) {
  return `名字是${username}`;
};
let userMap = new Map([
  ["zhangsan", filterUser("zhangsan")],
  ["lisi", filterUser("lisi")],
  ["xiaoming", filterUser("xiaoming")],
  ["xiaowang", filterUser("xiaowang")],
]);
console.log(userMap.get("zhangsan"));   // 名字是zhangsan

Recommend some common JavaScript syntax sugar

Arrow function


/**
 * 箭头函数
 *
 * */
function userInfo(name, age) {
  return `名字是:${name},年龄是:${age}`;
}
let userInfo = (name, age) => `名字是:${name},年龄是:${age}`;
console.log(userInfo("zhangsan", "23"));

Ternary operator handler

function log1() {
  console.log(1);
}
function log2() {
  console.log(2);
}
let num = 2;
if (num === 1) {
  log1();
} else {
  log2();
}
num === 1 ? log1() : log2();

Function default parameter handling

let getUser = (name = "zhangsan", age = 23) =>
      `名字是:${name},年龄是:${age}`;

console.log("默认参数", getUser());
console.log("传参", getUser("lisi", 29));

Data type conversion

let num1 = +"123";
console.log(num1);

Null, undefined Boolean and other special value processing, use the combination of |!

/**
 *
 * Null、Undefined 布尔值等特殊值处理,使用||结合!
 *
 * */
let name1 = undefined;
let name2 = null;
let name3 = true;
let name4 = false;
let name5 = "lisi";
console.log(name1 || "其他人"); // 其他人
console.log(name2 || "其他人"); // 其他人
console.log(name3 || "其他人"); // true
console.log(!name3 || "其他人"); // 其他人
console.log(name4 || "其他人"); // 其他人
console.log(name5 || "其他人"); // lisi
console.log(!name5 || "其他人"); // 其他人

Chain judgment operator

?. During the operation of the operator, it will be executed from left to right first. Whether the object on the left is null or undefined. If yes, the operation will no longer be performed to the right, but will return undefined

?. During the operation of the operator, it will be executed from left to right first. Whether the object on the left is null or undefined. If yes, the operation will no longer be performed to the right, but will return undefined

For more chain judgment operators, please refer to

Chain judgment operator

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining


let user = {
  name: "zhangsan",
  children: { name: "lisi", children: { name: "xiaoming" } },
};
let name1 = user?.name;
let name2 = user?.children?.name;
let name3 = user?.children?.children?.name;
console.log(name1);
console.log(name2);
console.log(name3);

Null value merge operator??

concept

Null merge operator (?) Is a logical operator. When the operand on the left is null or undefined, it returns the operand on the right. Otherwise, it returns the operand on the left.
Unlike the logical or operator (|), the logical or operator returns the right operand when the left operand is false.
If you use 𞓜 to set default values for some variables, you may encounter unexpected behavior. For example, when it is a false value (for example, ” or 0).

  • Null merge operator (?) Is a logical operator. When the operand on the left is null or undefined, it returns the operand on the right. Otherwise, it returns the operand on the left.
  • Unlike the logical or operator (|), the logical or operator returns the right operand when the left operand is false.
  • If you use 𞓜 to set default values for some variables, you may encounter unexpected behavior. For example, when it is a false value (for example, ” or 0).

const foo = null ?? "default string";
const test = undefined ?? "default string";
const test1 = 123 ?? "default string";
console.log(test); // "default string"
console.log(foo); // "default string"
console.log(test1); // 123
const baz = 0 ?? 42;
console.log(baz); // 0
const str = "" ?? 42;
const str1 = "" || 42;
console.log(str); // ""
console.log(str1); // 42

Summary

  • The above are some suggestions for if code optimization. If else is sometimes relatively cumbersome, but it is also a more direct judgment statement
  • Whether to optimize the if statement or to do it according to the specific business scenario requires personal judgment
  • The syntax sugar of JavaScript can save some tedious judgment or semantics in the daily development process
  • ECMA syntax of ES6 or higher version has been updated a lot. For some syntax extensions, it still provides a lot of help in the development process.

Source address

  • 码云 https://gitee.com/lewyon/vue-note

码云 https://gitee.com/lewyon/vue-note

  • githup https://github.com/akari16/vue-note

githup https://github.com/akari16/vue-note

Blog address: < strong > if statement optimization and some grammar sugar tips in JavaScript < / strong >

Welcome to the official account: programmer boo, who updates some front-end introductory articles from time to time

Creation is not easy. Please indicate the source and author for reprint.