做者:Zander Shirley翻譯:瘋狂的技術宅javascript
原文:https://dev.to/zandershirley/...前端
未經容許嚴禁轉載java
我一直在尋找提升效率的新方法。程序員
JavaScript 老是充滿使人出乎意料的驚喜。面試
arguments 對象是函數內部可訪問的相似數組的對象,其中包含傳遞給該函數的參數的值。segmentfault
但它與其餘數組不一樣,咱們能夠訪問其元素值並得到長度,可是不能在其上使用其餘的數組方法。數組
幸運的是,咱們能夠將其轉換爲常規數組:服務器
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()
我曾經在函數的開頭聲明本身的變量,只是爲了不在出現任何意外錯誤的狀況下獲得 undefined
。
function doSomething(arg1){ arg1 = arg1 || 32; // 若是變量還沒有設置,則 arg1 將以 32 做爲默認值 }
逗號運算符( ,
)用來評估其每一個操做數(從左到右)並返回最後一個操做數的值。
let x = 1; x = (x++, x); console.log(x); // expected output: 2 x = (2, 3); console.log(x); // expected output: 3
你能夠調整數組大小或清空數組。
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 愛好者,咱們能夠經過使用帶有展開運算符的 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 技巧或竅門要分享嗎?