[JS] JavaScript 小技巧筆記
實用
使用連續等於
會先從後面賦值,才往前賦值
overtime = house = listingDetail = {...}
轉址
keywords: redirect
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
How to redirect to another webpage? @ StackOverflow
檢驗效能(計時)
keywords: performance
方法一:使用內建函式
keywords: new Date().getTime()
// test performance function
const testPerformance = (testName, testFunction) => {
const startTime = new Date().getTime();
let i = 0;
while (i < 10000000) {
i++;
testFunction();
}
const endTime = new Date().getTime();
console.log(testName, endTime - startTime, 'ms');
};
// 執行測試
testPerformance('jsonStringify', jsonStringify);
// jsonStringify total time 59 ms
// 要測試的功能
function jsonStringify() {
JSON.stringify({ foo: name });
}
原始的概念:
let start;
let end;
start = new Date();
// Do something here
for (var i = 0; i < 1000; i++) {
Math.sqrt(i);
}
end = new Date();
console.log('Operation took ' + (end.getTime() - start.getTime()) + ' msec');
getTime @ MDN
方法二:使用 chrome devtool 的函式
keywords: console.time(timerName)
, console.timeEnd(timerName)
const timeTaken = (callback) => {
console.time('timer');
const r = callback();
console.timeEnd('timer');
return r;
};
timeTaken(() => {
// Do something here
for (var i = 0; i < 1000; i++) {
Math.sqrt(i);
}
});
資料結構
型別轉換(Type Transform | Type Coercion)
轉數值
keywords: Number(obj)
, parseInt(<string>, <radix>)
Cast to Number in Javascript using the Unary (+) Operator @ Medium
可以使用 Number(obj)
;如果使用 parseInt(<sting>, <radix>)
,則務必要給予 radix | 進位
參數,另外不建議使用 +
或 >>
:
const inputValue = '4';
// good
const val = Number(inputValue);
// good
const val = parseInt(inputValue, 10);
實際例子
// 有小數點時
let str = '23.1';
~~str; // 23
parseInt(str, 10); // 23
Number(str); // 23.1
// 數值後面有單位時
let str = '25px';
~~str; // 0
parseInt(str, 10); // 25
Number(str); // NaN
// 數值前面有單位時
let str = 'p25';
~~str; // 0
parseInt(str, 10); // NaN
Number(str); // NaN
// 編號
let str = '0010';
~~str; // 10
parseInt(str, 10); // 10
Number(str); // 10
22.3 Numbers: Use
Number
for type casting andparseInt
always with a radix for parsing strings. @ airbnb
轉字串
keywords: String(obj)
let reviewScore = 9;
// good
const totalScore = String(this.reviewScore);
// bad: typeof totalScore is "object" not "string"
// const totalScore = new String(reviewScore);
// bad: invokes this.reviewScore.valueOf()
// const totalScore = reviewScore + '';
// bad: isn’t guaranteed to return a string
// const totalScore = reviewScore.toString();
22.2 eslint:
no-new-wrappers
@ airbnb
轉布林(Boolean)
keywords: Boolean()
, !!
const age = 0;
// best
const hasAge = !!age;
// good
const hasAge = Boolean(age);
// wrong: is an Object
// const hasAge = new Boolean(age);
22.6 @ airbnb
Number 和 String 函數 @ MDN What is the difference between parseInt() and Number()? @ StackOverflow
其他
避免字串中正則表達式的反斜線被過濾
keywords: backslash
, escape
, regex
, string
regex = 'apple';
console.log(regex); // apple
/**
* 避免反斜線被過濾
**/
// 方法一:使用兩次反斜線來跳脫
regex = '\\apple';
console.log(regex); // \apple
// 方法二:使用 String.raw``
String.raw`\apple`;
Native JavaScript Buffer to NodeJS Buffer
new Blob([Uint8Array.from(fs.readFileSync($('#screen-video').attr('src'))).buffer]);