JS常用技巧

2021-10-12 03:00:11 字數 1697 閱讀 4771

三元運算子:

let hungry =

true

;let eat = hungry ?

'yes'

:'no'

;數字和字串互**

let num =15;

let s = num +"";

let n =

+s;// 相當於 0 + 字串

物件和陣列互**

let arr =

["value1"

,"value2"

,"value3"];

let arrobject =

;let key = object.

keys

(arrobject)

;let value = object.

values

(arrobject)

;let entry = object.

entries

(arrobject)

;填充陣列:

let arraysize =5;

let filledarray =

newarray

(arraysize)

.fill

(null).

map(()

=>()

);let filledarray1 =

newarray

(arraysize)

.fill()

;刪除重複項:

let array =

[100,23

,23,23

,23,67

,45];

let outputarray = array.

from

(new

set(array));

檢查是否為陣列:

let arr =[1

,3,5

];console.

log(

typeof arr)

;console.

log(array.

isarray

(arr));

判斷是否為數字

isnan

():判斷是否不為數字,但是會把null、空格、空字串按0來處理,所以先去除

let num =1;

// 'a', '', ' ', null, undefined, nan

if(num ===

""|| num ==

null

)consoole.

log(

isnan

(num));

物件的動態屬性:

let dynamic =

"value"

;let user =

;遍歷物件:

let age =

let o = object.

keys

(age);o.

foreach

(key => age[key]++)

;短路條件:

let docs =

true

;function

gotodocs()

docs &&

gotodocs()

;使用^檢查數字是否相等:

let a =

123;

if(a^

123)

JS常用技巧

獲取事件的產生dom var source event.srcelement ie var source event.target 火狐等其他瀏覽器 source blur 使用例項1 varesrc if window.event else 使用例項2 if event.srcelement es...

JS 陣列常用技巧

刪除陣列的重複項 var uniquefruits array.from new set fruits console.log 刪除陣列的重複項 uniquefruits 替換陣列中的特定值 var usernames 小組1 小組2 小組3 小組4 小組5 usernames.splice 0,2...

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