本篇文章給大家分享的是有關JavaScript的10個實用小技巧分別是哪些,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
我一直在尋找提高效率的新方法。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){ arg1arg1 = arg1 || 32; // 如果變量尚未設置,則 arg1 將以 32 作為默認值 }
5. 逗號運算符
逗號運算符( ,)用來評估其每個操作數(從左到右)并返回最后一個操作數的值。
let x = 1; x = (x++, x); console.log(x); // expected output: 2 x = (2, 3); console.log(x); // expected output: 3
6. 用 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 愛好者,我們可以通過使用帶有展開運算符的 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]
以上就是JavaScript的10個實用小技巧分別是哪些,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。