首頁  >  文章  >  web前端  >  JS 中 9 個強大主流寫法(各種 Hack 寫法)

JS 中 9 個強大主流寫法(各種 Hack 寫法)

Guanhui
Guanhui轉載
2020-05-15 09:28:152931瀏覽

JS 中 9 個強大主流寫法(各種 Hack 寫法)

1. 全域替換

#我們知道,字串函數replace () 只取代第一次出現的情況。

您可以透過在正規表示式的末尾新增 /g 來替換所有出現的內容。

var example = "potato potato";
console.log(example.replace(/pot/, "tom")); 
// "tomato potato"
console.log(example.replace(/pot/g, "tom")); 
// "tomato tomato"

2. 提取唯一值

透過使用 Set 物件和展開運算符,我們可以建立一個只有唯一值的新陣列。

var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]

3. 將數字轉換為字串

我們只需要連接一組空引號。

var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number); 
// string

4. 將字串轉換為數字

我們需要的只有 運算子。

需要注意的一點是只適用於 “字串數字”。

the_string = "123";
console.log(+the_string);
// 123
the_string = "hello";
console.log(+the_string);
// NaN

5. 隨機排列數組中的元素

我每天都在洗牌

var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(my_list.sort(function() {
    return Math.random() - 0.5
})); 
// [4, 8, 2, 9, 1, 3, 6, 5, 7]

6. 多維數組扁平化

只需使用擴充運算子。

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries); 
// [1, 2, 5, 6, 7, 9]

7. 短路條件

讓我們來看這個例子:

if (available) {
    addToCart();
}

只需將變數與函數一起使用即可將其縮短:

available && addToCart()

8. 動態屬性名稱

我一直以為我必須先宣告一個物件才能指派動態屬性。

const dynamic = 'flavour';
var item = {
    name: 'Coke',
    [dynamic]: 'Cherry'
}
console.log(item); 
// { name: "Coke", flavour: "Cherry" }

9. 使用 length 去調整或清空一個陣列

我們主要重寫了陣列的長度。

如果我們想要調整陣列的大小:

var entries = [1, 2, 3, 4, 5, 6, 7];  
console.log(entries.length); 
// 7  
entries.length = 4;  
console.log(entries.length); 
// 4  
console.log(entries); 
// [1, 2, 3, 4]

如果我們想要空數組:

var entries = [1, 2, 3, 4, 5, 6, 7]; 
console.log(entries.length); 
// 7  
entries.length = 0;   
console.log(entries.length); 
// 0 
console.log(entries); 
// []

推薦教學:《JS教學

以上是JS 中 9 個強大主流寫法(各種 Hack 寫法)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除