10個實用的JS技巧

將 arguments 對象轉換爲數組

arguments 對象是函數內部可訪問的類似數組的對象,其中包含傳遞給該函數的參數的值。

與其他數組不同,這裏我們可以訪問值並獲得長度(length),但是不能在其上使用其他數組方法。

幸運的是,我們可以將其轉換爲常規數組:

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

對數組中的所有值求和

我一開始想到的是使用一個循環,但是那樣會很浪費。

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

條件短路

我們有以下代碼:

if (hungry) {
    goToFridge();
}

我們可以進一步簡化代碼,同時使用變量和函數:

hungry && goToFridge()

對條件使用或(OR)邏輯

我以前在函數開始時聲明變量,只是爲了避免在出現意外錯誤時遇到 undefined。

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

逗號運算符

逗號運算符(,)用來計算其每個操作數(從左到右)並返回最後一個操作數的值。

let x = 1;
x = (x++, x);
console.log(x);
// expected output: 2
x = (2, 3);
console.log(x);
// expected output: 3

使用 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); // []

使用數組解構來交換值

解構賦值語法是一種 JavaScript 表達式,可以將數組中的值或對象中的屬性解包爲不同的變量。

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

隨機排列數組中的元素

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]

屬性名稱可以是動態的

你可以在聲明對象之前分配一個動態屬性。

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

過濾唯一值

對於所有 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 技巧或竅門要分享嗎?

英文原文

10 Practical JavaScript Tricks

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章