15 种有用的 TS & JS 简写代码


TypeScript 和 JavaScript 提供了一系列有用的简写代码,这些简写代码往往能减少代码行数,提高开发效率等。本文将回顾 15 种最常见的 TypeScript 和 JavaScript 的简写代码,并举例说明其用法。以下是这 15 种简写代码的清单:

  • 三元运算符
  • 短路求值
  • 空值合并操作符(??)
  • 字面量模板
  • 对象属性分配
  • 可选链运算符(?.)
  • 对象解构
  • 延展操作符(…)
  • 对象循环
  • 按位运算符(~)
  • 布尔值隐式转换(!!)
  • 箭头函数表达式及其隐式返回
  • 双按位NOT运算符(~~)
  • 指数幂运算符(**)
  • TypeScript 构造函数简写

1)三元运算符

主要用于替换 if...else... 语句,其格式如下 :

[condition] ? [true result] : [false result]

例如:

// 普通方式
const mark = 80

if (mark >= 65) {
  return "Pass"
else {
  return "Fail"
}

// 简写方式
const mark = 80

return mark >= 65 ? "Pass" : "Fail"

2)短路求值

同样用于替换 if...else... 语句,但它适用于需要对负值进行判断的场景,如果是负值则向后取值,直到取到正值为止。

例如:

// 普通方式
let str = ''
let finalStr

if (str !== null && str !== undefined && str != '') {
  finalStr = str
else {
  finalStr = 'default string'
}

// 简写方式
let str = ''
let finalStr = str || 'default string' // 'default string

3)空值合并操作符(??)

类似于短路求值,唯一的区别在于,这个只适用于对空值(Null)的判断,而非负值。

例如:

// 简写方式
let str = ''
let finaStr = str ?? 'default string' // ''
// 普通方式
let num = null
let actualNum

if (num !== null && num !== undefined) {
  actualNum = num
else {
  actualNum = 0
}

// 简写方式
let num = null
let actualNum = num ?? 0 // 0

4)字面量模板

这是 ES6 的特性,我们使用字面量模板(`${}`)来替换字符串用 + 的连接。

例如:

const name = 'Martin'
const hobby = 'to read'
const thing = 'books'

// 普通方式
const fullStr = name + ' loves ' + hobby + thing + '.' // 'Martin loves to read books.'
// 简写方式
const fullStr = `${name} loves ${hobby} ${thing}.`

5)对象属性分配

在 JavaScript 和 TypeScript 中,你可以使用对象属性的简写方式来给对象的属性赋值,但赋值对象必须和对象的属性保持一致。

例如:

// 普通方式
const obj = {
  x: 1,
  y: 2,
  z: 3
}

// 简写方式
const x = 8
const y = 10
const obj = { x, y }

6)可选链运算符(?.)

我们通常需要对对象的属性进行是否存在以及值的非空判断,可选链的方式能更好地实现。

例如:

const obj = {
  x: {
    y: 1,
    z: 2
  },
  others: [
    'test',
    'tested'
  ] 
}

// 普通方式
if (obj.hasProperty('others') && others.length >= 2) {
  console.log('2nd value in others: ', obj.others[1])
}

// 简写方式
console.log('2nd value in others: ', obj.others?.[1]) // 'tested'
console.log('3rd value in others: ', obj.others?.[2]) // undefined

7)对象解构

除了点运算符(.)另一种获取对象属性值的方式就是对象解构。

例如:

const obj = {
  x: {
    y: 1,
    z: 2
  },
  other: 'test string'
}

// 普通方式
console.log('Value of z in x: ', obj.x.z)
console.log('Value of other: ', obj.other)

// 简写方式
const {x, other} = obj
const {z} = x

console.log('Value of z in x: ', z)
console.log('Value of other: ', other)

const {x: myVar} = obj // 变量重命名
console.log('My renamed variable: ', myVar) // My renamed variable: 1

8)延展操作符(…)

可用于对数组的拼接,对象的合并等

例如:

// 普通方式
const arr = [1, 2, 3]
const biggerArr = [4,5,6].concat(arr)

const smallObj = {x: 1}
const otherObj = object.assign(smallObj, {y: 2})

// 简写方式
const arr = [1, 2, 3]
const biggerArr = [...arr, 4, 5, 6]

const smallObj = {x: 1}
const otherObj = {...smallObj, y: 2}

9)对象循环

有三种 for 循环的简写方式来迭代处理数组对象:

  • for...of 用来迭代访问数组
  • for...in 用来迭代访问数组的索引或者对象的属性(键)
  • Array.forEach 来处理数组元素和索引

例如:

// 普通方式
const arr = ['Yes''No''Maybe']

for (let i = 0; i < arr.length; i++) {
  console.log('Here is item: ', arr[i])
}

// 简写方式
for (let str of arr) {
  console.log('Here is item: ', str)
}

arr.forEach((str) => {
  console.log('Here is item: ', str)
})

for (let index in arr) {
  console.log(`Item at index ${index} is ${arr[index]}`)
}

// For object literals
const obj = {a: 1, b: 2, c: 3}

for (let key in obj) {
  console.log(`Value at key ${key} is ${obj[key]}`)
}

10)按位运算符(~)

我们通过 Array.indexOf 来检测数组中是否存在某一项,通常它返回一个大于 -1 的值来表示存在。我们可以使用按位运算符 ~ 来检测值在数组种的索引是否大于等于 0。

例如:

const arr = [10, 12, 14, 16]

const realNum = 10
const fakeNum = 20

const realNumIndex = arr.indexOf(realNum)
const noneNumIndex = arr.indexOf(fakeNum)

// 普通方式
if (realNumIndex > -1) {
  console.log(realNum, ' exists!')
else if (realNumIndex === -1) {
  console.log(realNum, ' does not exist!')
}

if (noneNumIndex > -1) {
  console.log(fakeNum, ' exists!')
else if (noneNumIndex === -1) {
  console.log(fakeNum, ' does not exist!')
}

// 简写方式
console.log(realNum + (~realNumIndex ? ' exists!' : ' does not exist!')
console.log(fakeNum + (~noneNumIndex ? ' exists!' : ' does not exist!')

11)布尔值隐式转换(!!)

在 JavaScript 中,你可以对任意变量使用 !! 来隐式转换变量类型为布尔型。

例如:

// 普通方式
const simpleInt = 3
const intAsBool = Boolean(simpleInt)

// 简写方式
const simpleInt = 3
const intAsBool = !!simpleInt // true

12)箭头函数表达式及其隐式返回

箭头函数有点类似于其他语言的 lambda 表达式,但要注意函数内部 this 的变化。

例如:

// 普通方式
function printStr(str) {
  console.log('This is a string: ', str)
}
printStr('Girl!')

// 简写方式
const printStr = (str) => {
  console.log('This is a string: ', str)
}
printStr('Girl!')

// TypeScript 简写方式(声明入参类型)
const printStr = (str: string) => {
  console.log('This is a string: ', str)
}
printStr('Girl!')

箭头函数的返回方式也有两种,一种是花括号则需要 return 语句, 另一种是圆括号,则不需要 return 语句,圆括号的表达式值即是返回值。

例如:

// 普通方式
function capitalize(name) {
  return name.toUpperCase()
}

function add(numA, numB) {
  return numA + numB
}

// 简写方式
const capitalize = (name) => name.toUpperCase()
const add = (numA, numB) => (numA + numB)

// TypeScript 简写方式
const capitalize = (name: string) => name.toUpperCase()
const add = (numA: number, numB: number) => (numA + numB)

13)双按位NOT运算符(~~)

其实就是 Math.floor() 方法的简写。

例如:

// 普通方式
const num = 4.5
const floorNum = Math.floor(num) // 4
// 简写方式
const num = 4.5
const floorNum = ~~num // 4

14)指数幂运算符(**)

其实就是 Math.pow() 方法的简写。

例如:

// 普通方式
const num = Math.pow(3, 4) // 81
// 简写方式
const num = 3 ** 4 // 81 

15)TypeScript 构造函数简写

是 TypeScript 特有的简写方式,不适用于 JavaScript

// 普通方式
class Person {
  private name: string
  public age: int
  protected hobbies: string[]

  constructor(name: string, age: int, hobbies: string[]) {
    this.name = name
    this.age = age
    this.hobbies = hobbies
  }
}

// 简写方式
class Person {
  constructor(
    private name: string,
    public age: int,
    protected hobbies: string[]
  ) {}
}

结论

以上就是一些最常用的 JavaScript 和 TypeScript 的简写方式,但同时请记住,使用简写方式并非在所有情况下的最佳选择,主要还是看使用场景,写代码关键还是干净、有效且有很好的可读性。

本文转自 https://zhuanlan.zhihu.com/p/521057686,如有侵权,请联系删除。



版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/20426.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!