今天小編要跟大家分享的文章是關(guān)于Web前端工程師應(yīng)該知道的JavaScript使用小技巧。任何一門技術(shù)在實(shí)際中都會有一些屬于自己的小技巧。同樣的,在使用JavaScript時(shí)也有一些自己的小技巧,只不過很多時(shí)候有可能容易被大家忽略。而在互聯(lián)網(wǎng)上,時(shí)不時(shí)的有很多同行朋友會總結(jié)(或收集)一些這方面的小技巧。
創(chuàng)新互聯(lián)公司主營紅安網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,app軟件開發(fā),紅安h5小程序設(shè)計(jì)搭建,紅安網(wǎng)站營銷推廣歡迎紅安等地區(qū)企業(yè)咨詢
今天在這篇文章中,小編會整理一些大家熟悉或不熟悉的有關(guān)于JavaScript的小技巧,希望能夠?qū)Υ蠹业膶W(xué)習(xí)和工作有所幫助。
一、數(shù)組
先來看使用數(shù)組中常用的一些小技巧。
01、數(shù)組去重
ES6提供了幾種簡潔的數(shù)組去重的方法,但該方法并不適合處理非基本類型的數(shù)組。對于基本類型的數(shù)組去重,可以使用...new
Set()來過濾掉數(shù)組中重復(fù)的值,創(chuàng)建一個(gè)只有唯一值的新數(shù)組。
constarray=[1,1,2,3,5,5,1]
constuniqueArray=[...newSet(array)];
console.log(uniqueArray);
Result:(4)[1,2,3,5]
這是ES6中的新特性,在ES6之前,要實(shí)現(xiàn)同樣的效果,我們需要使用更多的代碼。該技巧適用于包含基本類型的數(shù)組:undefined、null、boolean、string和number。如果數(shù)組中包含了一個(gè)object,function或其他數(shù)組,那就需要使用另一種方法。
除了上面的方法之外,還可以使用Array.from(newSet())來實(shí)現(xiàn):
constarray=[1,1,2,3,5,5,1]
Array.from(newSet(array))
Result:(4)[1,2,3,5]
另外,還可以使用Array的.filter及indexOf()來實(shí)現(xiàn):
constarray=[1,1,2,3,5,5,1]
array.filter((arr,index)=array.indexOf(arr)===index)
Result:(4)[1,2,3,5]
注意,indexOf()方法將返回?cái)?shù)組中第一個(gè)出現(xiàn)的數(shù)組項(xiàng)。這就是為什么我們可以在每次迭代中將indexOf()方法返回的索引與當(dāng)索索引進(jìn)行比較,以確定當(dāng)前項(xiàng)是否重復(fù)。
02、確保數(shù)組的長度
在處理網(wǎng)格結(jié)構(gòu)時(shí),如果原始數(shù)據(jù)每行的長度不相等,就需要重新創(chuàng)建該數(shù)據(jù)。為了確保每行的數(shù)據(jù)長度相等,可以使用Array.fill來處理:
letarray=Array(5).fill('');
console.log(array);
Result:(5)["","","","",""]
03、數(shù)組映射
不使用Array.map來映射數(shù)組值的方法。
constarray=[
{
ame:'大漠',
email:'w3cplus@#'
},
{
ame:'Airen',
email:'airen@#'
}
]
constname=Array.from(array,({name})=name)
Result:(2)["大漠","Airen"]
04、數(shù)組截?cái)?/p>
如果你想從數(shù)組末尾刪除值(刪除數(shù)組中的最后一項(xiàng)),有比使用splice()更快的替代方法。
例如,你知道原始數(shù)組的大小,可以重新定義數(shù)組的length屬性的值,就可以實(shí)現(xiàn)從數(shù)組末尾刪除值:
letarray=[0,1,2,3,4,5,6,7,8,9]
console.log(array.length)
Result:10
array.length=4
console.log(array)
Result:(4)[0,1,2,3]
這是一個(gè)特別簡潔的解決方案。但是,slice()方法運(yùn)行更快,性能更好:
letarray=[0,1,2,3,4,5,6,7,8,9];
array=array.slice(0,4);
console.log(array);
Result:[0,1,2,3]
05、過濾掉數(shù)組中的falsy值
如果你想過濾數(shù)組中的falsy值,比如0、undefined、null、false,那么可以通過map和filter方法實(shí)現(xiàn):
constarray=[0,1,'0','1','大漠','#',undefined,true,false,null,'undefined','null',NaN,'NaN','1'+0]
array.map(item={
returnitem
}).filter(Boolean)
Result:(10)[1,"0","1","大漠","#",true,"undefined","null","NaN","10"]
06、獲取數(shù)組的最后一項(xiàng)
數(shù)組的slice()取值為正值時(shí),從數(shù)組的開始處截取數(shù)組的項(xiàng),如果取值為負(fù)整數(shù)時(shí),可以從數(shù)組末屬開始獲取數(shù)組項(xiàng)。
letarray=[1,2,3,4,5,6,7]
constfirstArrayVal=array.slice(0,1)
Result:[1]
constlastArrayVal=array.slice(-1)
Result:[7]
console.log(array.slice(1))
Result:(6)[2,3,4,5,6,7]
console.log(array.slice(array.length))
Result:[]
正如上面示例所示,使用array.slice(-1)獲取數(shù)組的最后一項(xiàng),除此之外還可以使用下面的方式來獲取數(shù)組的最后一項(xiàng):
console.log(array.slice(array.length-1))
Result:[7]
07、過濾并排序字符串列表
你可能有一個(gè)很多名字組成的列表,需要過濾掉重復(fù)的名字并按字母表將其排序。
在我們的例子里準(zhǔn)備用不同版本語言的JavaScript
保留字的列表,但是你能發(fā)現(xiàn),有很多重復(fù)的關(guān)鍵字而且它們并沒有按字母表順序排列。所以這是一個(gè)完美的字符串列表(數(shù)組)來測試我們的JavaScript小知識。
varkeywords=['do','if','in','for','new','try','var','case','else','enum','null','this','true','void','with','break','catch','class','const','false','super','throw','while','delete','export','import','return','switch','typeof','default','extends','finally','continue','debugger','function','do','if','in','for','int','new','try','var','byte','case','char','else','enum','goto','long','null','this','true','void','with','break','catch','class','const','false','final','float','short','super','throw','while','delete','double','export','import','native','public','return','static','switch','throws','typeof','boolean','default','extends','finally','package','private','abstract','continue','debugger','function','volatile','interface','protected','transient','implements','instanceof','synchronized','do','if','in','for','let','new','try','var','case','else','enum','eval','null','this','true','void','with','break','catch','class','const','false','super','throw','while','yield','delete','export','import','public','return','static','switch','typeof','default','extends','finally','package','private','continue','debugger','function','arguments','interface','protected','implements','instanceof','do','if','in','for','let','new','try','var','case','else','enum','eval','null','this','true','void','with','await','break','catch','class','const','false','super','throw','while','yield','delete','export','import','public','return','static','switch','typeof','default','extends','finally','package','private','continue','debugger','function','arguments','interface','protected','implements','instanceof'];
因?yàn)槲覀儾幌敫淖兾覀兊脑剂斜?,所以我們?zhǔn)備用高階函數(shù)叫做filter,它將基于我們傳遞的回調(diào)方法返回一個(gè)新的過濾后的數(shù)組。回調(diào)方法將比較當(dāng)前關(guān)鍵字在原始列表里的索引和新列表中的索引,僅當(dāng)索引匹配時(shí)將當(dāng)前關(guān)鍵字push到新數(shù)組。
最后我們準(zhǔn)備使用sort方法排序過濾后的列表,sort只接受一個(gè)比較方法作為參數(shù),并返回按字母表排序后的列表。
在ES6下使用箭頭函數(shù)看起來更簡單:
constfilteredAndSortedKeywords=keywords
.filter((keyword,index)=keywords.lastIndexOf(keyword)===index)
.sort((a,b)=a
這是最后過濾和排序后的JavaScript保留字列表:
console.log(filteredAndSortedKeywords);
Result:['abstract','arguments','await','boolean','break','byte','case','catch','char','class','const','continue','debugger','default','delete','do','double','else','enum','eval','export','extends','false','final','finally','float','for','function','goto','if','implements','import','in','instanceof','int','interface','let','long','native','new','null','package','private','protected','public','return','short','static','super','switch','synchronized','this','throw','throws','transient','true','try','typeof','var','void','volatile','while','with','yield']
08、清空數(shù)組
如果你定義了一個(gè)數(shù)組,然后你想清空它。通常,你會這樣做:
letarray=[1,2,3,4];
functionemptyArray(){
array=[];
}
emptyArray();
但是,這有一個(gè)效率更高的方法來清空數(shù)組。你可以這樣寫:
letarray=[1,2,3,4];
functionemptyArray(){
array.length=0;
}
emptyArray();
09、拍平多維數(shù)組
使用...運(yùn)算符,將多維數(shù)組拍平:
10、從數(shù)組中獲取最大值和最小值
可以使用Math.max和Math.min取出數(shù)組中的最大小值和最小值:
constnumbers=[15,80,-9,90,-99]
constmaxInNumbers=Math.max.apply(Math,numbers)
constminInNumbers=Math.min.apply(Math,numbers)
console.log(maxInNumbers)
Result:90
console.log(minInNumbers)
Result:-99
另外還可以使用ES6的...運(yùn)算符來完成:
constnumbers=[1,2,3,4];
Math.max(...numbers)
Result:4
Math.min(...numbers)
Result:1
二、對象
在操作對象時(shí)也有一些小技巧。
01、使用...運(yùn)算符合并對象或數(shù)組中的對象
同樣使用ES的...運(yùn)算符可以替代人工操作,合并對象或者合并數(shù)組中的對象。
//合并對象
constobj1={
ame:'大漠',
url:'#'
}
constobj2={
ame:'airen',
age:30
}
constmergingObj={...obj1,...obj2}
Result:{name:"airen",url:"#",age:30}
//合并數(shù)組中的對象
constarray=[
{
ame:'大漠',
email:'w3cplus@#'
},
{
ame:'Airen',
email:'airen@#'
}
]
constresult=array.reduce((accumulator,item)={
return{
...accumulator,
[item.name]:item.email
}
},{})
Result:{大漠:"w3cplus@#",Airen:"airen@#"}
02、有條件的添加對象屬性
不再需要根據(jù)一個(gè)條件創(chuàng)建兩個(gè)不同的對象,以使它具有特定的屬性。為此,使用...操作符是最簡單的。
constgetUser=(emailIncluded)={
return{
ame:'大漠',
blog:'w3cplus',
...emailIncluded{email:'w3cplus@#'}
}
}
constuser=getUser(true)
console.log(user)
Result:{name:"大漠",blog:"w3cplus",email:"w3cplus@#"}
constuserWithoutEmail=getUser(false)
console.log(userWithoutEmail)
Result:{name:"大漠",blog:"w3cplus"}
03、解構(gòu)原始數(shù)據(jù)
你可以在使用數(shù)據(jù)的時(shí)候,把所有數(shù)據(jù)都放在一個(gè)對象中。同時(shí)想在這個(gè)數(shù)據(jù)對象中獲取自己想要的數(shù)據(jù)。
在這里可以使用ES6的Destructuring特性來實(shí)現(xiàn)。比如你想把下面這個(gè)obj中的數(shù)據(jù)分成兩個(gè)部分:
constobj={
ame:'大漠',
blog:'w3cplus',
email:'w3cplus@#',
joined:'2019-06-19',
followers:45
}
letuser={},userDetails={}
({name:user.name,email:user.email,...userDetails}=obj)
{name:"大漠",blog:"w3cplus",email:"w3cplus@#",joined:"2019-06-19",followers:45}
console.log(user)
Result:{name:"大漠",email:"w3cplus@#"}
console.log(userDetails)
Result:{blog:"w3cplus",joined:"2019-06-19",followers:45}
04、動(dòng)態(tài)更改對象的key
在過去,我們首先必須聲明一個(gè)對象,然后在需要?jiǎng)討B(tài)屬性名的情況下分配一個(gè)屬性。在以前,這是不可能以聲明的方式實(shí)現(xiàn)的。不過在ES6中,我們可以實(shí)現(xiàn):
constdynamicKey='email'
letobj={
ame:'大漠',
blog:'w3cplus',
[dynamicKey]:'w3cplus@#'
}
console.log(obj)
Result:{name:"大漠",blog:"w3cplus",email:"w3cplus@#"}
05、判斷對象的數(shù)據(jù)類型
使用Object.prototype.toString配合閉包來實(shí)現(xiàn)對象數(shù)據(jù)類型的判斷:
constisType=type=target=`[object${type}]`===Object.prototype.toString.call(target)
constisArray=isType('Array')([1,2,3])
console.log(isArray)
Result:true
上面的代碼相當(dāng)于:
functionisType(type){
returnfunction(target){
return`[object${type}]`===Object.prototype.toString.call(target)
}
}
isType('Array')([1,2,3])
Result:true
或者:
constisType=type=target=`[object${type}]`===Object.prototype.toString.call(target)
constisString=isType('String')
constres=isString(('1'))
console.log(res)
Result:true
06、檢查某對象是否有某屬性
當(dāng)你需要檢查某屬性是否存在于一個(gè)對象,你可能會這樣做:
varobj={
ame:'大漠'
}
if(obj.name){
console.l
現(xiàn)在有很多各種各樣的JavaScript庫,但這里將介紹7個(gè)很優(yōu)秀的可用于你下一個(gè)JavaScript項(xiàng)目的庫。
儀表盤是用于目標(biāo)或業(yè)務(wù)流程的視覺指示工具,也用于切割雜亂無章的數(shù)據(jù),從而分割出要點(diǎn)的重要工具。它可幫助評估信息,并及時(shí)做出正確的決定。實(shí)時(shí)可視化的儀表盤由圖標(biāo)、測繪圖、圖形符號,以及數(shù)據(jù)表格等組成。
目前有一些開源或商業(yè)的庫用于創(chuàng)建儀表盤。在本文中,我們將會展示一些可幫助創(chuàng)建美觀且可自定義的儀表盤的JavaScript庫。
1.Gridster.js
Gridster是一個(gè)jQuery插件,可以從跨多個(gè)列的元素構(gòu)建直觀的可拖拽布局。
它可以讓你從網(wǎng)格中動(dòng)態(tài)添加或刪除小部件,甚至可以獲得一個(gè)具有所有小部件位置的對象的JavaScript數(shù)組,從而可以在以后使用這些數(shù)組來加載小部件。
2.angular-gridster
這是一個(gè)用于AngularJS的格子狀小部件的實(shí)現(xiàn)。它具有jQuerygridster插件等功能,也具有一些其他的功能。
它完全使用Angular指令重寫,還可以使用Angular的數(shù)據(jù)綁定功能。
3.gridstack.js
gridstack.js是一個(gè)用于小部件布局的jQuery插件,靈感來自gridster.js。這是一個(gè)可拖放的多列網(wǎng)格,可讓你構(gòu)建可拖拽的響應(yīng)式Bootstrapv3的友好布局,
它還適用于knockout.js,angular.js和觸摸設(shè)備。
4.jQueryGridly
Gridly是一個(gè)jQuery插件,電腦培訓(xùn)建議可用于拖放以及在網(wǎng)格中調(diào)整大小。
5.Packery
Packery是一個(gè)JavaScript庫和jQuery插件,可用于生成無縫且可拖拽的布局。它使用bin-packing算法來填充空隙。
它適合用于創(chuàng)建一個(gè)可拖拽的儀表盤和無縫的“磚石圖像畫廊”布局。
首先要對點(diǎn)數(shù)據(jù)進(jìn)行分類,哪些在區(qū)級顯示,哪些在鎮(zhèn)級顯示,可以使用一個(gè)字段rank劃分等級,比如區(qū)級為1,鎮(zhèn)級為2。然后對圖層根據(jù)rank列使用唯一值符號化。然后設(shè)置圖層的ScaleRange。舉個(gè)例子,顯示整個(gè)區(qū)時(shí)比例尺是1:100k,顯示整個(gè)鎮(zhèn)時(shí)比例尺是1:25K。那么添加兩個(gè)點(diǎn)圖層,數(shù)據(jù)源相同。一個(gè)點(diǎn)圖層在1:100k時(shí)可見,此時(shí)只顯示rank值為1的點(diǎn)數(shù)據(jù),另一個(gè)點(diǎn)圖層在1:25K時(shí)可見,此時(shí)顯示rank值為1和2的點(diǎn)數(shù)據(jù)。