JavaSript-Map

示例一:Map()

var map = new Map();

map.set(1, 1);
map.set(2, 4);
map.set(3, 9);

console.log("3: " + map.has(3)); // 3: true
console.log("3: " + map.get(3)); // 3: 9
console.log("4: " + map.has(4)); // 4: false

map.delete(3);
console.log("3: " + map.get(3)); // 3: undefined 

示例二:array-like

var students = {}; // Cannot be undefined.

function init() {
  for (var i = 0; i < 5; i++) {
    students[i + 1] = {
      name : "name" + i,
      city : "city" + i
    }
  }
}

function print() {
  var id = 0;
  for (var id in students) {
    console.log(id + ": [name=" + students[id].name + ",city=" + students[id].city + "]");
  }
}

function printSingle(id) {
  if (id in students) {
    console.log("Found. " + id + ": [name=" + students[id].name + ",city=" + students[id].city + "]");
  } else {
    console.log("Not found " + id + ".");
  }
}

init();

/*
1: [name=name0,city=city0]
2: [name=name1,city=city1]
3: [name=name2,city=city2]
4: [name=name3,city=city3]
5: [name=name4,city=city4]*/
print();

//Found. 3: [name=name2,city=city2]
printSingle(3);

//Not found 30.
printSingle(30);

delete students[3];

/*
1: [name=name0,city=city0]
2: [name=name1,city=city1]
4: [name=name3,city=city3]
5: [name=name4,city=city4]*/
print();

//length: undefined
console.log("length: " + students.length);

發佈留言