ECMA6中的map()

第一种用法,也是最简单直接的,一个一个摞,然后get出来

demo1

var m = new Map();
    m.set('name','mazhaoyang');
    m.set('sex','nan');
    console.log(m.get('name'));//mazhaoyang
    console.log(m);//Map { name: "mazhaoyang", sex: "nan" }

接下来就获取key值桑,

var map = new Map();
map.set('name','mazhaoyang');
map.set('sex','nan');
var keys = map.keys();
for(let key of keys){
    console.log(key)    //name  sex
}

key值和val值都获取

var map = new Map();
    map.set('name','mazhaoyang');
    map.set('sex','nan');
var entries = map.entries();//遍历实体
for(let [key,value] of entries){
    console.log(key,value);
}
//    name mazhaoyang
//    sex nan

更像jquery封装的$.each()方法

回顾一下jquery

var arr = [
    {"id":"1","sex":"nan"},
    {"id":"2","sex":"nv"},
    {"id":"3","sex":"buzhidao"}
]; $.each(arr, function(idx, obj) { console.log(obj.sex)
}); //nan //nv //buzhidao

操作JSON

    var json = {"id":"1","sex":"nan","name":"mazhaoyang"};
    $.each(json, function(key,val) {
        console.log(key,val)
    });
    //id 1
    //sex nan
    //name mazhaoyang

看起来jquery的$.each方法更方便不是么,但是感觉jquery被淘汰已经是写在时间表上的事情了。

随机浏览