js常用小技巧

2022-07-02 15:12:10 字數 1311 閱讀 6770

陣列扁平化

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().split('

,')); //

["1", "2", "3", "4", "5", "6", "7", "8"]

原來join()、tostring()函式式可以跨越層級的,於是便有了方式2、 3

一句**生成0-100的陣列

const arr1 = [...array(100).keys()]

一句**求字串反轉

let str = '

hello 秦愛德';

console.log([...str].reverse().join(

'')) //

德愛秦 olleh

計算相同元素出現次數且以鍵值對形式展示

const names = ['

alice

', '

bob', '

tiff

', '

bruce

', '

alice'];

const countnames = names.reduce((allname,name) =>

else

return

allname;

}, {});

console.log(countnames);

//

數字補0操作

function totwo(value,len = 2

) console.log(totwo('8

')); //

08function newtotwo(value,len = 2

) `).slice(-len);

} console.log(newtotwo(

1)); //

01

js開發中常用小技巧

function getradomnum min,max function getradomfromarr arr function getarray len 等同於 function getarray len console.log arr var arr 1,2,3,4,5,6,7,a dsfs...

JS開發中常用的小技巧

123 functiongetradomnum min,max 12 34functiongetradomfromarr arr 12 345functiongetarray len 等同於 12 3456 7functiongetarray len console.log arr 12 34var...

JS常用技巧

三元運算子 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 obj...