https://codepen.io/Rouoxo/pen/XWzMgvY
(1) 易轉型
console.log(!!0); // false
console.log(parseInt("169.99cm")); // 169
console.log(parseFloat("169.99cm")); // 169.99
console.log(String(false)); // "false"
console.log(Object(169.99)); // Number {169.99}
(2) 判斷Array
// 利用Array.isArray()函式
// 利用instanceof運算子判斷是否為Array類別
// 利用Object.prototype.toString()函式判斷字串
console.log(Array.isArray([])); // true
console.log([] instanceof Array); // true
console.log(Object.prototype.toString.call([]) == "[object Array]"); // true 好用
var Vtuber = ["茸茸鼠", "阿罵"];
if (typeof Vtuber === "object" && Vtuber.constructor === Array) {
console.log("Vtuber是真正的陣列");
}
https://codepen.io/Rouoxo/pen/qBVrPaa?editors=0012
function getPlayerObj(name, progress) {
return {
sayHi() {
return `Hi, I am ${name}`;
},
};
}
console.log(getPlayerObj("OneJar", 23).sayHi()); // "Hi, I am OneJar"
https://codepen.io/Rouoxo/pen/jOaBGwR?editors=0011
var、具名函式 可使用Hoisting
let 、const、匿名函式、=>(為匿名函式) 無法使用Hoisting
無法在函式宣告之前就使用
console.log("eee+fff", eee() + fff()); //hoisting
function eee(cry = 123) {
return cry;
}
function fff(cry = 456) {
return cry;
}
https://codepen.io/Rouoxo/pen/oNoZGow?editors=0012
var testModule = (function () {
var counter = 0;
return {
incrementCounter: function () {
return counter++;
},
// 語法糖 物件
resetCounter() {
console.log("counter value prior to reset: " + counter);
counter = 0;
},
};
})();
//test
testModule.incrementCounter();
testModule.incrementCounter();
testModule.incrementCounter();
testModule.resetCounter(); //counter value prior to reset: 3
prototype 似繼承 給拿走的變數使用
let Crash = function () {
this.name = "Crash";
this.age = 18;
this.secret = {
weight: 100,
fn: function () {
console.log(this); // {weight: 100, fn: ƒ}
},
};
};
let myCrash = new Crash();
// 接著針對函式的原型添加屬性
Crash.prototype.cat = 3;
Crash.prototype.dog = 4;
console.log(Crash); // 只有原本的資料
console.log("myCrash", myCrash); // 有新增的
myCrash.secret.fn(); // {weight: 100, fn: ƒ}
參閱:
https://www.wfublog.com/2012/12/javascript-awful-parts.html
https://codepen.io/Rouoxo/pen/eYevGPJ?editors=0012
全域變數
分號錯誤
保留字
typeof
parseInt
+
浮點數
undefined 與 NaN
hasOwnProperty()
eval