JS優(yōu)化技巧

null、undefined 和空值檢查并分配默認(rèn)值

但是要反例如果在數(shù)據(jù)為0(或者空字符串的時(shí)候也要返回?cái)?shù)據(jù)),此時(shí)用||運(yùn)算符就會(huì)搞錯(cuò)了,返回的是默認(rèn)值了:

// 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();

綜上:
&&為取假運(yùn)算,從左到右依次判斷,如果遇到一個(gè)假值,就返回假值,以后不再執(zhí)行,否則返回最后一個(gè)真值
||為取真運(yùn)算,從左到右依次判斷,如果遇到一個(gè)真值,就返回真值,以后不再執(zhí)行,否則返回最后一個(gè)假值

擴(kuò)展:可選鏈接運(yùn)算符
//Longhand 
if (data && data.children && data.children[0] && data.children[0].title) {
    // I have a title!
} 
//Shorthand 
//對(duì)于靜態(tài)屬性用法是object?.property。對(duì)于動(dòng)態(tài)屬性object?.[expression] 
 let data;
console.log(data?.children?.[0]?.title) // undefined

data  = {children: [{title:'codercao'}]}
console.log(data?.children?.[0]?.title) // codercao
用于多個(gè)條件判斷的 && 操作符

結(jié)果僅在變量為 true 的情況下才調(diào)用函數(shù),則可以使用 && 運(yùn)算符。

比較后返回
// 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 簡(jiǎn)化
// 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]();
對(duì)象屬性賦值
let test1 = 'a'; 
let test2 = 'b';
//Longhand 
let obj = {test1: test1, test2: test2}; 
//Shorthand 
let obj = {test1, test2};
將字符串轉(zhuǎn)成數(shù)字

可以用*1(乘以1)來(lái)轉(zhuǎn)化為數(shù)字(實(shí)際上是調(diào)用.valueOf方法) 然后使用Number.isNaN來(lái)判斷是否為NaN,或者使用 a !== a 來(lái)判斷是否為NaN,因?yàn)?NaN !== NaN。也可以使用+來(lái)轉(zhuǎn)化字符串為數(shù)字

//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

解構(gòu)賦值
//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遍歷數(shù)組和字符串
for…in遍歷對(duì)象。For…in遍歷對(duì)象包括所有繼承的屬性,所以如果只是想使用對(duì)象本身的屬性需要做一個(gè)判斷

比較大小

比較大小使用 a - b > 0的方式更好,用a > b有時(shí)候會(huì)出現(xiàn)錯(cuò)誤

錯(cuò)誤用法
'20' > '100'  // true

預(yù)期結(jié)果
'20' - '100' > 0   // false

//數(shù)組排序算法
arr.sort((a, b ) =>{
  return a-b 
})
取整與判斷奇偶數(shù)
1.3 | 0         // 1
-1.9 | 0        // -1

const num=3;
!!(num & 1)                    // true
!!(num % 2)                    // true
精確到指定位數(shù)的小數(shù)

將數(shù)字四舍五入到指定的小數(shù)位數(shù)。使用 Math.round() 和模板字面量將數(shù)字四舍五入為指定的小數(shù)位數(shù)。省略第二個(gè)參數(shù) decimals ,數(shù)字將被四舍五入到一個(gè)整數(shù)。

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
數(shù)組的對(duì)象解構(gòu)
const csvFileLine = '1997,John Doe,US,john@doe.com,New York';
const { 2: country, 4: state } = csvFileLine.split(',');
 
country            // US
state            // New Yourk
對(duì)象數(shù)組按照某個(gè)屬性查詢最大值
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}))
使用解構(gòu)刪除對(duì)象某個(gè)屬性
let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
 
console.log(cleanObject);    // {el1: '1', el2: '2', el3: '3'}
使用Object.assign設(shè)置默認(rèn)對(duì)象
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}
對(duì)象計(jì)算屬性

在微信小程序還是React中,我們需要根據(jù)某個(gè)條件去修改某個(gè)數(shù)據(jù)

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

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

leader:深拷貝有這5個(gè)段位,你只是青銅段位?還想漲薪?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容