9 個極其強大的 JavaScript 技巧
點擊上方“逆鋒起筆”,公眾號回復(fù) pdf
領(lǐng)取大佬們推薦的學(xué)習(xí)資料
作者 | Fatima Nawaz
譯者 | 王強
策劃 | 田曉旭
所謂 hacker 方法,就是一種不斷改進和迭代的構(gòu)建方法。有著 hacker 精神的程序員相信事物總有改進的余地,沒有什么是完美的存在。每一段代碼都有進一步優(yōu)化的空間,每一個操作都有更便捷的技巧。
下面列舉一些非常強大的 JavaScript hack 技巧。
我們知道 string.Replace() 函數(shù)只會替換第一個項目。
var example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato"
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]
var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string
用 + 運算符即可。
the_string = "123";
console.log(+the_string);
// 123
the_string = "hello";
console.log(+the_string);
// NaN
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]關(guān)注公眾號 逆鋒起筆,回復(fù) pdf,下載你需要的各種學(xué)習(xí)資料。
var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9]
if (available) {
addToCart();
}
available && addToCart()
const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" }關(guān)注公眾號 逆鋒起筆,回復(fù) pdf,下載你需要的各種學(xué)習(xí)資料。
基本上就是覆蓋數(shù)組的 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);
// []
你也在搜尋 JavaScript hacker 技巧的話,希望本文對你有幫助。
https://medium.com/javascript-in-plain-english/9-extremely-powerful-javascript-hacks-eed8ed11af5
用 Java 寫了一個類 QQ 界面聊天小項目,可在線聊天!
點個『在看』支持下
評論
圖片
表情
