关闭

JavaSript-Map

标签: Javascriptmaparray-like
104人阅读 评论(0) 收藏 举报
分类:

示例一: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);
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:219671次
    • 积分:5779
    • 等级:
    • 排名:第4467名
    • 原创:375篇
    • 转载:14篇
    • 译文:0篇
    • 评论:19条
    文章分类
    最新评论