9 個(gè)極其強(qiáng)大的 JavaScript 技巧
? ?作者 | Fatima Nawaz所謂 hacker 方法,就是一種不斷改進(jìn)和迭代的構(gòu)建方法。有著 hacker 精神的程序員相信事物總有改進(jìn)的余地,沒有什么是完美的存在。每一段代碼都有進(jìn)一步優(yōu)化的空間,每一個(gè)操作都有更便捷的技巧。
下面列舉一些非常強(qiáng)大的 JavaScript hack 技巧。
我們知道 string.Replace() 函數(shù)只會(huì)替換第一個(gè)項(xiàng)目。
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用 + 運(yùn)算符即可。
the_string = "123";
console.log(+the_string);
// 123
the_string = "hello";
console.log(+the_string);
// NaNvar?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]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" }基本上就是覆蓋數(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 技巧的話,希望本文對(duì)你有幫助。
最后
關(guān)注公眾號(hào)【前端宇宙】,每日獲取好文推薦 添加微信,入群交流
評(píng)論
圖片
表情
