Immutable.js
Immutable.js它内部实现了一套完整的 Persistent Data Structure
fromJS()
将数组或者对象转换为Immutable
let map=Immutable.fromJS({ a:1, b:2 }); let list=Immutable.fromJS([ { a:1, b:2 } ]); console.log(map); console.log(list);
is()
检测是否相等,和Object.is()是有区别的
let map1=Immutable.Map({a:1}); let map2=Immutable.Map({a:1}); console.log(map1===map2); //false console.log(Object.is(map1,map2)); //false console.log(Immutable.is(map1,map2)); //true
List是个索引集合
List.isList() 判断是否为List集合
let list=Immutable.List([1,2,3]); console.log(Immutable.List.isList(list)); //true
List.of()创建一个集合
console.log(Immutable.List.of([1,2,3]));
List大小
let list=Immutable.List([1,2,3]); console.log(list.size); //3 console.log(list.count()); //3
获取List索引元素
console.log(list.get(0)); console.log(list.get(-1)); //反向索引
更新
let list=Immutable.List([0, 0, [1, 2]]); let list1=list.set(0,2); let list2=list.update(1,v=>2);
遍历
let list=Immutable.List([0, 0, [1, 2]]); list.forEach((item,index,array)=>{ console.log(item); console.log(index); console.log(array); return false; //返回false跳出,true继续 });
查找
let list=Immutable.List([0,0, [1, 2]]); //返回一个匹配值 console.log(list.find(x=>x===0)); //返回匹配值的集合 console.log(list.filter(x=>x===0)); //返回不匹配值的集合 console.log(list.filterNot(x=>x===0));
Map
创建
let map=Immutable.Map({a:1,b:2}); let map1=Immutable.fromJS({a:1,b:2});
判断
let map=Immutable.Map({a:1,b:2}); console.log(Immutable.Map.isMap(map)); //true
获取
let map=Immutable.Map({a:1,b:2}); let map1=Immutable.fromJS({a:{b:2},b:2}); console.log(map.get('a')); //1 //获取树 console.log(map1.getIn(['a','b'])); //2
更新
let map=Immutable.Map({a:1,b:2}); let map1=map.set('a',2); let map2=map.update('a',value=>3); console.log(map1); console.log(map2); let map3=Immutable.fromJS({ a:{ b:1 } }); let map4=map3.updateIn(['a','b'],value=>2); console.log(map4.toJS()); let map5=map3.setIn(['a','b'],5); console.log(map5.toJS());
合并
let map=Immutable.Map({a:1,b:2}); let map3=Immutable.fromJS({ a:{ b:1 } }); let map4=map.merge(map3); console.log(map4.toJS());
判断是否存在key
let map=Immutable.Map({a:1,b:2}); console.log(map.has('a'))
查找
let map=Immutable.Map({a:1,b:2}); let map1=map.filter(a=>a===1); let map2=map.find(a=>a===1); console.log(map1.toJS()); console.log(map2);
遍历
let map=Immutable.Map({a:1,b:2}); map.forEach((value,key,object)=>{ console.log(value); console.log(key); console.log(object); });