我們知道js中有一些假值:false, null, 0, 「」, undefined, nan,怎樣把陣列中的假值快速過濾呢,可以使用boolean建構函式來進行一次轉換
const
compact
= arr => arr.
filter
(boolean)
compact([
0,1,
false,2
,'',3
,'a'
,'e'*23
,nan
,'s',34
])// [ 1, 2, 3, 'a', 's', 34 ]
可以使用雙位操作符來替代正數的 math.floor(),替代負數的 math.ceil()。雙否定位操作符的優勢在於它執行相同的操作執行速度更快。
math.
floor
(4.9
)===
4//true
// 簡寫為:~~
4.9===
4//true
不過要注意,對正數來說 ~~ 運算結果與 math.floor() 運算結果相同,而對於負數來說與 math.ceil()的運算結果相同:
~
~4.5
// 4
math.
floor
(4.5
)// 4
math.
ceil
(4.5
)// 5~~
-4.5
// -4
math.
floor(-
4.5)
// -5
math.
ceil(-
4.5)
// -4
對乙個數字 |0可以取整,負數也同樣適用, num|0
1.3|0
// 1
-1.3|0
// -1
對乙個數字 &1可以判斷奇偶數,負數也同樣適用, num&1
const num=3;
!!(num &1)
// true!!
(num %2)
// true
很多時候,你希望統計陣列中重複出現項的個數然後用乙個物件表示。那麼你可以使用reduce方法處理這個陣列。
下面的**將統計每一種車的數目然後把總數用乙個物件表示。
var cars =
['bmw'
,'benz'
,'benz'
,'tesla'
,'bmw'
,'toyota'];
var carsobj = cars.
reduce
(function
(obj, name),)
;carsobj;
// =>
//之後有了在補充 js使用小技巧
1.收藏時用圖示顯示 2.td內容實現不換行 只要使用nowrap屬性即可 3.獲得客戶端檔案大小 4.動態刪除元素 img1.removenode true 5.模擬按鍵 var wshshell new activexobject wscript.shell wshshell.sendkeys ...
js常用小技巧
陣列扁平化 const arr 1,2,3,4,5,6,7,8 console.log arr.flat infinity 1,2,3,4,5,6,7,8 console.log arr.join split 1 2 3 4 5 6 7 8 console.log arr.tostring spli...
js實戰小技巧彙總
記錄實戰開發中使用到的js技巧 二 陣列 如下 示例 let x string value indexof 1 小數點的位置 let y string value length x 有幾位小數 如下 react changeevent e onchange e this.changeevent e ...