美文网首页
JS优化技巧

JS优化技巧

作者: 小姑凉喜欢无脸男 | 来源:发表于2021-06-22 18:13 被阅读0次
null、undefined 和空值检查并分配默认值

但是要反例如果在数据为0(或者空字符串的时候也要返回数据),此时用||运算符就会搞错了,返回的是默认值了:

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';

//返例
let test3 = 0;
let test4 = test3 || 'no data';//'no data

注意:该方式主要用于 null 或 undefined 的检查,特别需要注意tmp=0或者tmp=‘0’都是false。

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //it will check empty string,null and undefined too
if (test1)

//Longhand 
if (test1) {
 callMethod(); 
} 
//Shorthand 
test1 && callMethod();

综上:
&&为取假运算,从左到右依次判断,如果遇到一个假值,就返回假值,以后不再执行,否则返回最后一个真值
||为取真运算,从左到右依次判断,如果遇到一个真值,就返回真值,以后不再执行,否则返回最后一个假值

扩展:可选链接运算符
//Longhand 
if (data && data.children && data.children[0] && data.children[0].title) {
    // I have a title!
} 
//Shorthand 
//对于静态属性用法是object?.property。对于动态属性object?.[expression] 
 let data;
console.log(data?.children?.[0]?.title) // undefined

data  = {children: [{title:'codercao'}]}
console.log(data?.children?.[0]?.title) // codercao
用于多个条件判断的 && 操作符

结果仅在变量为 true 的情况下才调用函数,则可以使用 && 运算符。

比较后返回
// Longhand
let test;
function checkReturn() {
    if (!(test === undefined)) {
        return test;
    } else {
        return callMe('test');
    }
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
    console.log(val);
}
// Shorthand
function checkReturn() {
    return test || callMe('test');
}
switch 简化
// Longhand
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // And so on...
}
// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};
data[something] && data[something]();
对象属性赋值
let test1 = 'a'; 
let test2 = 'b';
//Longhand 
let obj = {test1: test1, test2: test2}; 
//Shorthand 
let obj = {test1, test2};
将字符串转成数字

可以用*1(乘以1)来转化为数字(实际上是调用.valueOf方法) 然后使用Number.isNaN来判断是否为NaN,或者使用 a !== a 来判断是否为NaN,因为 NaN !== NaN。也可以使用+来转化字符串为数字

//Longhand 
let test1 = parseInt('123'); 
let test2 = parseFloat('12.3'); 
//Shorthand 
//*1
'32' * 1            // 32
'ds' * 1            // NaN
null * 1            // 0
undefined * 1    // NaN
1  * { valueOf: ()=>'3' }        // 3
//使用+
+ ''                    // 0
+ 'ds'                    // NaN
+ null              // 0
+ undefined    // NaN
+ { valueOf: ()=>'3' }    // 3

解构赋值
//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;
for…in,for…of

for…of遍历数组和字符串
for…in遍历对象。For…in遍历对象包括所有继承的属性,所以如果只是想使用对象本身的属性需要做一个判断

比较大小

比较大小使用 a - b > 0的方式更好,用a > b有时候会出现错误

错误用法
'20' > '100'  // true

预期结果
'20' - '100' > 0   // false

//数组排序算法
arr.sort((a, b ) =>{
  return a-b 
})
取整与判断奇偶数
1.3 | 0         // 1
-1.9 | 0        // -1

const num=3;
!!(num & 1)                    // true
!!(num % 2)                    // true
精确到指定位数的小数

将数字四舍五入到指定的小数位数。使用 Math.round() 和模板字面量将数字四舍五入为指定的小数位数。省略第二个参数 decimals ,数字将被四舍五入到一个整数。

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
round(1.345, 2)                 // 1.35   Number(1.345e2e-2)
round(1.345, 1)                 // 1.3

// 此处e2表示乘以10的2次方 
1.23e1   //12.3
1.23e2   // 123
123.45e-2  // 1.2345
数组的对象解构
const csvFileLine = '1997,John Doe,US,john@doe.com,New York';
const { 2: country, 4: state } = csvFileLine.split(',');
 
country            // US
state            // New Yourk
对象数组按照某个属性查询最大值
var array=[
        {
            "index_id": 119,
            "area_id": "18335623",
            "name": "满意度",
            "value": "100"
        },
        {
            "index_id": 119,
            "area_id": "18335624",
            "name": "满意度",
            "value": "20"
        },
        {
            "index_id": 119,
            "area_id": "18335625",
            "name": "满意度",
            "value": "80"
        }];

Math.max.apply(Math, array.map(function(o) {return o.value}))
使用解构删除对象某个属性
let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
 
console.log(cleanObject);    // {el1: '1', el2: '2', el3: '3'}
使用Object.assign设置默认对象
const someObject = {
    title: null,
    subTitle: "Subtitle",
    buttonColor: null,
    disabled: true
 };
 function creteOption(someObject) {
    const newObject = Object.assign({
      title: "Default Title",
      subTitle: "Default Subtitle",
      buttonColor: "blue",
      disabled: true
    },someObject)
    return newObject
 }
 console.log(creteOption(someObject));//{title: 'Default Title', subTitle: 'Subtitle', buttonColor: 'blue', disabled: true}
对象计算属性

在微信小程序还是React中,我们需要根据某个条件去修改某个数据

if (type === 'boy') {
  this.setData({
    boyName: name
  })
} else if (type === 'girl') {
  this.setData({
    girlName: name
  })
}

this.setData({
  [`${type}Name`]: name
})
深拷贝

leader:深拷贝有这5个段位,你只是青铜段位?还想涨薪?

相关文章

  • 2021JavaScript 优化技巧

    2021JS优化技巧[https://juejin.cn/post/6937828220033040415] 1....

  • JS优化技巧

    null、undefined 和空值检查并分配默认值 但是要反例如果在数据为0(或者空字符串的时候也要返回数据),...

  • Python-02进阶-07代码优化技巧

    代码优化技巧 优化原则 核心技巧 其他技巧 Python 代码性能优化技巧 常用代码优化技巧 sort()优于so...

  • JS性能优化技巧

    脚本应该放在页面元素代码之后无论当前 JavaScript 代码是内嵌还是在外链文件中,页面的下载和渲染都必须停下...

  • JS优化小技巧

    转载知乎:https://zhuanlan.zhihu.com/p/402817988[https://zhuan...

  • Cocos Creator如何优化包体大小

    Cocos Creator 包体的组成与优化技巧: 1: 代码体积(引擎+ 业务逻辑代码setting.js)大头...

  • Unity优化技巧集合

    知乎作者:Mack Unity优化技巧(上)Unity优化技巧(中)Unity优化技巧(下)

  • UITableView 的优化技巧

    UITableView 的优化技巧 UITableView 的优化技巧

  • Js 常用的优化技巧

    1. async 和 await 代替 promise (即异步改同步) 2. Object.is 比较两个值是否...

  • 34种JS优化技巧

    1. 带有多个条件的 if 语句 把多个值放在一个数组中,然后调用数组的 includes 方法。 2. 简化 i...

网友评论

      本文标题:JS优化技巧

      本文链接:https://www.haomeiwen.com/subject/yaqmyltx.html