20個(gè)JS簡(jiǎn)寫(xiě)技巧提升工作效率
前言:
最近看了一些簡(jiǎn)化JS代碼的文章,其中有一篇覺(jué)得還不錯(cuò),但是是英文的,也看了一些中文翻譯,一個(gè)是一字一句翻譯太生硬,沒(méi)有變成自己的東西,另外就是后面作者有新增沒(méi)有及時(shí)更新,于是我按照自己的語(yǔ)言翻譯整理成此文,本文特點(diǎn)以言簡(jiǎn)意賅為主
當(dāng)同時(shí)聲明多個(gè)變量時(shí),可簡(jiǎn)寫(xiě)成一行
//Longhand let x; let y = 20; //Shorthand let x, y = 20;
利用解構(gòu),可為多個(gè)變量同時(shí)賦值
//Longhand let a, b, c; a = 5; b = 8; c = 12; //Shorthand let [a, b, c] = [5, 8, 12];
巧用三元運(yùn)算符簡(jiǎn)化if else
//Longhand
let marks = 26;
let result;
if (marks >= 30) {
result = 'Pass';
} else {
result = 'Fail';
}
//Shorthand
let result = marks >= 30 ? 'Pass' : 'Fail';
使用||運(yùn)算符給變量指定默認(rèn)值
本質(zhì)是利用了||運(yùn)算符的特點(diǎn),當(dāng)前面的表達(dá)式的結(jié)果轉(zhuǎn)成布爾值為false時(shí),則值為后面表達(dá)式的結(jié)果
//Longhand
let imagePath;
let path = getImagePath();
if (path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}
//Shorthand
let imagePath = getImagePath() || 'default.jpg';
使用&&運(yùn)算符簡(jiǎn)化if語(yǔ)句
例如某個(gè)函數(shù)在某個(gè)條件為真時(shí)才調(diào)用,可簡(jiǎn)寫(xiě)
//Longhand
if (isLoggedin) {
goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();
使用解構(gòu)交換兩個(gè)變量的值
let x = 'Hello', y = 55; //Longhand const temp = x; x = y; y = temp; //Shorthand [x, y] = [y, x];
適用箭頭函數(shù)簡(jiǎn)化函數(shù)
//Longhand
function add(num1, num2) {
return num1 + num2;
}
//Shorthand
const add = (num1, num2) => num1 + num2;
需要注意箭頭函數(shù)和普通函數(shù)的區(qū)別
使用字符串模板簡(jiǎn)化代碼
使用模板字符串代替原始的字符串拼接
//Longhand
console.log('You got a missed call from ' + number + ' at ' + time);
//Shorthand
console.log(`You got a missed call from ${number} at ${time}`);
多行字符串也可使用字符串模板簡(jiǎn)化
//Longhand
console.log('JavaScript, often abbreviated as JS, is a\n' +
'programming language that conforms to the \n' +
'ECMAScript specification. JavaScript is high-level,\n' +
'often just-in-time compiled, and multi-paradigm.'
);
//Shorthand
console.log(`JavaScript, often abbreviated as JS, is a
programming language that conforms to the
ECMAScript specification. JavaScript is high-level,
often just-in-time compiled, and multi-paradigm.`
);
對(duì)于多值匹配,可將所有值放在數(shù)組中,通過(guò)數(shù)組方法來(lái)簡(jiǎn)寫(xiě)
//Longhand
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// Execute some code
}
// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
// Execute some code
}
// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) {
// Execute some code
}
巧用ES6對(duì)象的簡(jiǎn)潔語(yǔ)法
例如:當(dāng)屬性名和變量名相同時(shí),可直接縮寫(xiě)為一個(gè)
let firstname = 'Amitav';
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};
使用一元運(yùn)算符簡(jiǎn)化字符串轉(zhuǎn)數(shù)字
//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
//Shorthand
let total = +'453';
let average = +'42.6';
使用repeat()方法簡(jiǎn)化重復(fù)一個(gè)字符串
//Longhand
let str = '';
for(let i = 0; i < 5; i ++) {
str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello
// Shorthand
'Hello '.repeat(5);
// 想跟你說(shuō)100聲抱歉!
'sorry\n'.repeat(100);
使用雙星號(hào)代替Math.pow()
//Longhand const power = Math.pow(4, 3); // 64 // Shorthand const power = 4**3; // 64
使用雙波浪線運(yùn)算符(~~)代替Math.floor()
//Longhand const floor = Math.floor(6.8); // 6 // Shorthand const floor = ~~6.8; // 6
需要注意,~~僅適用于小于2147483647的數(shù)字
巧用擴(kuò)展操作符(...)簡(jiǎn)化代碼
簡(jiǎn)化數(shù)組合并
let arr1 = [20, 30]; //Longhand let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80] //Shorthand let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]
單層對(duì)象的拷貝
let obj = {x: 20, y: {z: 30}};
//Longhand
const makeDeepClone = (obj) => {
let newObject = {};
Object.keys(obj).map(key => {
if(typeof obj[key] === 'object'){
newObject[key] = makeDeepClone(obj[key]);
} else {
newObject[key] = obj[key];
}
});
return newObject;
}
const cloneObj = makeDeepClone(obj);
//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));
//Shorthand for single level object
let obj = {x: 20, y: 'hello'};
const cloneObj = {...obj};
尋找數(shù)組中的最大和最小值
// Shorthand const arr = [2, 8, 15, 4]; Math.max(...arr); // 15 Math.min(...arr); // 2
使用for in和for of來(lái)簡(jiǎn)化普通for循環(huán)
let arr = [10, 20, 30, 40];
//Longhand
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//Shorthand
//for of loop
for (const val of arr) {
console.log(val);
}
//for in loop
for (const index in arr) {
console.log(arr[index]);
}
簡(jiǎn)化獲取字符串中的某個(gè)字符
let str = 'jscurious.com'; //Longhand str.charAt(2); // c //Shorthand str[2]; // c
移除對(duì)象屬性
let obj = {x: 45, y: 72, z: 68, p: 98};
// Longhand
delete obj.x;
delete obj.p;
console.log(obj); // {y: 72, z: 68}
// Shorthand
let {x, p, ...newObj} = obj;
console.log(newObj); // {y: 72, z: 68}
使用arr.filter(Boolean)過(guò)濾掉數(shù)組成員的值falsey
let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];
//Longhand
let filterArray = arr.filter(function(value) {
if(value) return value;
});
// filterArray = [12, "xyz", -25, 0.5]
// Shorthand
let filterArray = arr.filter(Boolean);
// filterArray = [12, "xyz", -25, 0.5]
到此這篇關(guān)于20個(gè)JS簡(jiǎn)寫(xiě)技巧提升工作效率的文章就介紹到這了,更多相關(guān)JS簡(jiǎn)寫(xiě)技巧內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ligerUI---ListBox(列表框可移動(dòng)的實(shí)例)
下面小編就為大家分享一篇ligerUI---ListBox(列表框可移動(dòng)的實(shí)例),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2017-11-11
使用validate.js實(shí)現(xiàn)表單數(shù)據(jù)提交前的驗(yàn)證方法
這篇文章主要介紹了使用validate.js實(shí)現(xiàn)表單數(shù)據(jù)提交前的驗(yàn)證方法,文中給大家提供了完整代碼,需要的朋友可以參考下2018-09-09
javaScript(JS)替換節(jié)點(diǎn)實(shí)現(xiàn)思路介紹
獲取要替換的節(jié)點(diǎn),這種方法只適用于IE瀏覽器以及適用于各種瀏覽器的寫(xiě)法,感興趣的朋友可以參考下哈2013-04-04
學(xué)習(xí)javascript面向?qū)ο?理解javascript對(duì)象
這篇文章主要介紹了javascript對(duì)象,學(xué)習(xí)javascript面向?qū)ο?,感興趣的小伙伴們可以參考一下2016-01-01
JavaScript事件循環(huán)同步任務(wù)與異步任務(wù)
這篇文章主要介紹了JavaScript事件循環(huán)同步任務(wù)與異步任務(wù),文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07
js實(shí)現(xiàn)人民幣大寫(xiě)金額形式轉(zhuǎn)換
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)人民幣大寫(xiě)金額形式轉(zhuǎn)換的相關(guān)資料,需要的朋友可以參考下2016-04-04
JS樹(shù)形菜單組件Bootstrap TreeView使用方法詳解
這篇文章主要為大家詳細(xì)介紹了js組件Bootstrap TreeView使用方法,本文一部分針對(duì)于bootstrap的treeview的實(shí)踐,另一部分是介紹自己寫(xiě)的樹(shù)形菜單,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12

