JavaScipt 是非常流行的程式語言,其中有些少見技巧,但還不錯用,這篇文章會分享八個,給您參考看看!
函數繼承就是先寫一個基礎函數,再寫一個擴充函數,來擴充屬性與方法,會像這樣:
// Base function
function Drinks(data) {
var that = {}; // Create an empty object
that.name = data.name; // Add it a "name" property
return that; // Return the object
};
// Fuction which inherits from the base function
function Coffee(data) {
// Create the Drinks object
var that = Drinks(data);
// Extend base object
that.giveName = function() {
return 'This is ' + that.name;
};
return that;
};
// Usage
var firstCoffee = Coffee({ name: 'Cappuccino' });
console.log(firstCoffee.giveName());
// Output: "This is Cappuccino"
.map()
有一個替代方案,就是 .from()
:
let dogs = [
{ name: ‘Rio’, age: 2 },
{ name: ‘Mac’, age: 3 },
{ name: ‘Bruno’, age: 5 },
{ name: ‘Jucas’, age: 10 },
{ name: ‘Furr’, age: 8 },
{ name: ‘Blu’, age: 7 },
]
let dogsNames = Array.from(dogs, ({name}) => name);
console.log(dogsNames); // returns [“Rio”, “Mac”, “Bruno”, “Jucas”, “Furr”, “Blu”]
通常,要讓數字轉為字串,會這樣寫
let num = 4
let newNum = num.toString();
然後字串轉數字,會這樣寫
let num = "4"
let stringNumber = Number(num);
但有個更快的寫法是:
let num = 15;
let numString = num + ""; // number to string
let stringNum = + numString; // string to number
在 javascript 中,我們可以改寫 length 內建方法,直接設定一個新值。
舉個例:
let array_values = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(array_values.length);
// 8
array_values.length = 5;
console.log(array_values.length);
// 5
console.log(array_values);
// [1, 2, 3, 4, 5]
還能用來清空陣列:
let array_values = [1, 2, 3, 4, 5, 6, 7,8];
console.log(array_values.length);
// 8
array_values.length = 0;
console.log(array_values.length);
// 0
console.log(array_values);
// []
陣列解構讓陣列或物件的屬性,可以拆出來到變數中。還可以用它來交換兩個元素,舉例如下:
let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // result -> 2
console.log(b) // result -> 1
這個技巧很簡單。比方說,我創建了一個包含重複元素的陣列,然後我想刪除重複項:
const array = [1, 3, 2, 3, 2, 1, true, false, true, 'Kio', 2, 3];
const filteredArray = [...new Set(array)];
console.log(filteredArray) // [1, 3, 2, true, false, "Kio"]
可以這樣寫:
const names = ["Kio", "Rio", "Mac"];
// Long Version
for (let i = 0; i < names.length; i++) {
const name = names[i];
console.log(name);
}
// Short Version
for (let name of names) console.log(name);
下面這張圖是 google 用秒數提示效能:
https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7ed89oyhcyyjhqirvc6.png
在 JavaScript 中也能做到,就像這樣:
const firstTime = performance.now();
something();
const secondTime = performance.now();
console.log(`The something function took ${secondTime - firstTime} milliseconds.`);
以上八個技巧,希望對您有幫助!