前端代码优化

1.带有多的条件的if的语句 逻辑 || 的简写

if (x == 'true' || x == '2523' || x == '小明') {
    // logic
}

//Array.includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false
if (['true', '2523', '小明'].includes(x)) {
    // logic
}

2.简化 if true…else 条件的写法,可以运用三元运算符

if (x > 100) {
    test = true
} else {
    test = false
}

test = x > 100 ? true : false

3.声明变量

let test1;
let test2 = 1
// 简写
let test3, test4 = 1

// 给多个变量进行赋值
let test1 = 1, test3 = 2, test4 = 3;
// 简化 
let [test1, test3, test4] = [1, 2, 3]

4.null 和 undefined 的空置检查当这个数据已知是 null 或者是 undefined 可以这样写

if (test1 != null || test1 !== undefined || test1 !== '') {
    // logic
    let test2 = test1
}
let test2 = test1 || ''

// 还可以基于 ?? 操作符 如果左边的值为 null 或 undefined 就返回右边的值,如果左边的值为默认值就返回左边的值
const test = null ?? 'default'
console.log(test) // default

// || 与 ?? 判断的方法不同:
// 使用 ?? 时,只有One为 null 或者 undefined 时才会返回 Two;
// 使用 || 时,One会先转化为布尔值判断,为true时返回One , false 返回Two
const test6 = 0 ?? 1
console.log(test6) // 0

5.操作赋值符

let test1 = 3
test1 = test1 + 1
test3 = test1 - 1
test4 = test1 * 20

// 简化
test1++
test1--
test1 *= 20

6.判断值是否存在

if (val) { } // 存在 
if (!val) { }  // 不存在

7.条件判断 && 判断如果为 true 调用函数

if (test1) {
    fn()
}
//test1 为true  执行 fn()
test1 && fn()
//test1 为false 执行 fn()
test1 || fn()

8.拼接简化

let arr1 = [1, 3]
let arr2 = [4, 5]
console.log(arr2.concat(arr1))
console.log([...arr1, ...arr2])

9.克隆数组

let arr4 = [1, 234, 4, 88]
let arr5 = arr4.slice()

let arr4 = [1, 234, 4, 88]
let arr5 = [...arr4]

10.switch 的简化

function fn1() { console.log(1) }
function fn2() { console.log(2) }
function fn3() { console.log(3) }
let data1 = 1
switch (data1) {
    case 1:
        fn1()
        break
    case 2:
        fn2()
        break
    case 'h':
        fn3()
        break
    default:
        console.log('啥也是不是')
}

// 简化
let data2 = 1
var data = {
    1: fn1,
    2: fn2,
    'h': fn3,
}
data[data2] && data[data2]()

11.Object.assign()设置默认对象

const menuConfig = {
  title: null,
  body: 'Bar',
  buttonText: null,
  cancellable: true
};

function createMenu(config) {
  config.title = config.title || 'Foo';
  config.body = config.body || 'Bar';
  config.buttonText = config.buttonText || 'Baz';
  config.cancellable = config.cancellable === undefined ? config.cancellable : true;
}

createMenu(menuConfig);

-----------------------------

const menuConfig = {
  title: 'Order',
  // User did not include 'body' key
  buttonText: 'Send',
  cancellable: true
};

function createMenu(config) {
  config = Object.assign({
    title: 'Foo',
    body: 'Bar',
    buttonText: 'Baz',
    cancellable: true
  }, config);

  // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
  // ...
}

createMenu(menuConfig);

12.使用可搜索的名称

// 艹, 86400000 是什么鬼?
setTimeout(blastOff, 86400000);

// 将它们声明为全局常量 `const` 。
const MILLISECONDS_IN_A_DAY = 86400000;
setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

13.使用解释性的变量

const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);

const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);

14.使用默认变量替代短路运算或条件

function createMicrobrewery(name) {
  const breweryName = name || 'Hipster Brew Co.';
  // ...
}

function createMicrobrewery(breweryName = 'Hipster Brew Co.') {
  // ...
}

15,函数参数 (两个以下最理想)

function createMenu(title, body, buttonText, cancellable) {
  // ...
}

const menuConfig = {
  title: 'Foo',
  body: 'Bar',
  buttonText: 'Baz',
  cancellable: true
};

function createMenu(config) {
  // ...
}

16.使用解构赋值 解构对象里的属性

async Fn1(){
    const res = await getData() // 需用res.data才能使用
    const { data: res } = await getData() // 结构数据里的data赋值给res
}

that.wechat.name = res.data.weixin.name || ''
that.wechat.payAccount = res.data.weixin.payAccount || ''
that.wechat.phone = res.data.weixin.phone || ''
//解构赋值对象优化 注意上下文分号
({name:that.alipay.name,phone: that.alipay.phone, payAccount: that.alipay.payAccount} = res.data.alipay);

17.数组扁平化

//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

18.提前退出 和 提前返回

function printAnimalsDetails(animal) {
    var result = null
    if (animal) {
        if (animal.type) {
            if (animal.name) {
                if (animal.gender) {
                    result = `${animal.name} is a ${animal.gender} - ${animal.
                        type}`
                } else {
                    result = 'no anomal gender'
                }
            } else {
                result = 'no animal name'
            }
        } else {
            result = 'no animal type'
        }
    } else {
        result = 'no animal'
    }
    return result
}

// 提前退出 和 提前返回
const printAnimalsDetails = (animal) => {
    if (!animal.type) return "no animal type"
    if (!animal.name) return "no animal name"
    if (!animal.gender) return "no animal gender"
    return `${animal.name} is a ${animal.gender} - ${animal.type}`
}
文章链接:http://iwebg.cn/index.php/2023/07/20/%e5%89%8d%e7%ab%af%e4%bb%a3%e7%a0%81%e4%bc%98%e5%8c%96/

版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇