首頁  >  文章  >  web前端  >  JavaScript中10個實用小技巧(分享)

JavaScript中10個實用小技巧(分享)

青灯夜游
青灯夜游轉載
2021-01-04 17:55:262341瀏覽

JavaScript中10個實用小技巧(分享)

相關推薦:《javascript影片教學

#我一直在尋找提高效率的新方法。

而JavaScript 總是充滿出乎意料的驚喜。

1、將arguments物件轉換為陣列

#arguments 物件是函數內部可存取的類似陣列的對象,其中包含傳遞給該函數的參數的值。

但這與其他陣列不同,我們可以存取值並取得長度,但是不能對其使用其他陣列方法。

幸運的是,我們可以把它轉換成一個常規數組:

var argArray = Array.prototype.slice.call(arguments);

2、對數組中的所有值求和

我最初的直覺是使用循環,但是那樣做太費事了。

var numbers = [3, 5, 7, 2];
var sum = numbers.reduce((x, y) => x + y);
console.log(sum); // returns 17

3、條件短路

我們有以下程式碼:

if (hungry) {
    goToFridge();
}

透過將變數與函數一起使用,我們可以使其更短:

hungry && goToFridge()

4、對條件使用邏輯或||

我過去常常在函數的開頭聲明自己的變量,以避免在出現任何意外錯誤時出現undefined 的情況。

function doSomething(arg1){ 
    arg1 = arg1 || 32; // if it's not already set, arg1 will have 32 as a default value
}

5、逗號運算子

#逗號運算子( ,)可以評估其每個運算元(從左到右)並傳回最後一個操作數的值。

let x = 1;

x = (x++, x);

console.log(x);
// expected output: 2

x = (2, 3);

console.log(x);
// expected output: 3

6、使用length調整陣列大小

我們可以使用length屬性來調整陣列大小或清空陣列

var array = [11, 12, 13, 14, 15];  
console.log(array.length); // 5  

array.length = 3;  
console.log(array.length); // 3  
console.log(array); // [11,12,13]

array.length = 0;  
console.log(array.length); // 0  
console.log(array); // []

7、使用陣列解構交換值

解構賦值語法是一種JavaScript 表達式,可以將陣列中的值或物件中的屬性解壓縮為不同的變數。

let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // -> 2
console.log(b) // -> 1

8、隨機排列數組中的元素

#我每天我都在隨機排列

#隨機排列,隨機排列

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

9、屬性名稱可以是動態的

你可以在宣告物件之前指派動態屬性。

const dynamic = 'color';
var item = {
    brand: 'Ford',
    [dynamic]: 'Blue'
}
console.log(item); 
// { brand: "Ford", color: "Blue" }

10、過濾唯一值

#對於所有ES6愛好者,我們可以透過使用具有擴充運算子(spread)的Set物件來建立一個僅包含唯一值的新數組。

const my_array = [1, 2, 2, 3, 3, 4, 5, 5]
const unique_array = [...new Set(my_array)];
console.log(unique_array); // [1, 2, 3, 4, 5]

結束想法

負責遠比高效重要。

你的網站需要在所有瀏覽器中都可以使用。

你可以使用Endtest或其他類似工具來確保可以。

你呢?你有任何JavaScript技巧或訣竅要分享嗎?

英文原文網址:https://dev.to/zandershirley/10-practical-javascript-tricks-2b7h

作者:Zander Shirley

#更多程式相關知識,請造訪:程式設計入門! !

以上是JavaScript中10個實用小技巧(分享)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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