function
var exam = {}
console.log(exam)
exam = {
title: "數學測驗",
score: 95,
student: "Tea",
nickname: ["茶", "抹茶"],
notify: function () {
alert(exam.student + "考了" + exam.score + "分!")
}
}
console.log(exam.notify) // 沒加小括號(),只會印出 function 物件
/*
ƒ () {
alert(exam.student + "考了" + exam.score + "分!")
}
*/
exam.notify()
var score = {
math: 95,
english: 80,
chinese: 77,
avg: function () {
var total = score.math + score.english + score.chinese
return total / 3
}
}
console.log(score.avg())
var scores = [
{student: "Jason", score: 95},
{student: "Tom", score: 90},
{student: "Kate", score: 88},
]
console.log(scores[2].student + "考了" + scores[2].score + "分");
for
for(var i = 0; i < 10; i++){
console.log(i);
}
var scores = [
{student: "Jason", score: 95},
{student: "Tom", score: 90},
{student: "Kate", score: 88},
]
for(i = 0; i < scores.length; i++){
console.log("學生:", scores[i].student + "考了" , scores[i].score,"分")
}
存放Key
、Value
宣告時要用new
正確用法
var m = new Map();
m.set("name","Tea"); // 新增資料到Key中
console.log(m)
m.set("name","Pencil"); // 同樣的Key後面覆蓋前面
console.log(m)
console.log(m.has('name')); // true
console.log(m.get('name')); // Pencil
以下為在其他語言中看似正確,在JS裡卻是 錯誤的Map用法
(雖然可以用,但與上面的get、has就像兩個世界一樣毫無相干)
剛從其他語言轉過來時,覺得錯誤用法超級合理的。
var m = new Map();
m['name'] = "Tea";
m['name'] = "Pencil";
console.log(m['name']);
不過稍微看了一下,這錯誤的map用法是屬於Object
物件的屬性原生用法,
也許設計當初是怕與這搞混淆才區別開來吧。
var m = Object();
m['name'] = "123"
console.log(m['name']);
錯誤用法的Key、Value會跑到屬性欄位去
也許這段程式碼(在Chrome console上的輸出),能較容易理解兩者區別:
var m = new Map();
m['name1'] = "Tea";
m['name2'] = "Pencil";
console.log("錯誤用法:")
console.log(m);
m.set("name1","Tea");
m.set("name2","Pencil");
console.log("加上了正確用法:")
console.log(m)
七種迭代map的寫法
var m = new Map();
m.set("name1","Tea");
console.log(m)
m.set("name2","Pencil");
console.log(m)
console.log(m.size); // 2
console.log(m.keys()); // {"name1", "name2"}
for (var key of m.keys()){
console.log(key);
}
for (var value of m.values()){
console.log(value);
}
for (var [key, value] of m){
console.log(key, value);
}
for (var [key, value] of m.entries()){
console.log(key, value);
}
// 以上四種for迴圈,以下三種forEach
m.forEach(function (value){
console.log(value);
})
m.forEach(function (value, key){
console.log(value, key);
})
m.forEach(function (value, key, map){
console.log(value, key, map);
})