<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="./lib/immutable.4.0.0.js"></script> <title>不可变量</title> </head> <body> <div id="app"></div> <div id="box"> 持久化数据,使用结构共享,immutable对象不可被修改,修改后返回一个新的immutable新对象 </div> <script> console.log( Immutable ) console.log(Immutable.version,'版本号') // fromJS 把一个js对象转换成 immutable 对象 let imuobj = Immutable.fromJS({name:'lili',age:12,sex:'gril',hobby:['唱歌','跳舞','打豆豆']}) console.log(imuobj) console.log(imuobj.size) console.log(imuobj._root) console.log(imuobj._root.entries) console.log(imuobj._root.entries.length)
//toJS 把一个 immutable 对象转换成 js 对象
let tojs = imuobj.toJS()
console.log('tojs',tojs)
</script> </body> </html>
Map的增删改查
// 创建一个map对象 const map = Immutable.Map({name:'lili',age:12,mather:{name:'kate',age:32,height:'178cm'}}) console.log(map) // 增 // 方法一 let map1 = map.set({"other":"hello"}) console.log(map1) // 方法二 let map2 = map.setIn(["petdog","name"],"哈士奇") console.log(map2) console.log(JSON.parse(JSON.stringify(map2))) // 当对象属性是一个对象,并未该对象添加多个键值对时候 let map3 = map.setIn(["petcat","name"],"加菲猫").setIn(["petcat","color"],"花色").setIn(["petcat","sex"],"公猫") console.log(JSON.parse(JSON.stringify(map3))) // 删除 // 方法一 let mapdelete1 = map.delete('name') console.log('删除方法一 : ',JSON.parse(JSON.stringify(mapdelete1))) // {age: 12} // 方法二 let mapdelete2 = map.deleteIn(['name']) console.log(JSON.parse(JSON.stringify(mapdelete2))) // 删除对象的属性是对象时采用此方法比较合适 let mapdelete3 = map.deleteIn(['mather','age']) console.log(JSON.parse(JSON.stringify(mapdelete3))) // 修改 // 参数一:需要修改的属性名,参数二是一个函数 let mapmodify1 = map.update('name',(arg)=>{return arg="LUCY"}) console.log(JSON.parse(JSON.stringify(mapmodify1))) let mapmodify2 = map.updateIn(['mather','height'],(arg)=>{return arg ="168CM"}) console.log(JSON.parse(JSON.stringify(mapmodify2))) // 查询 let mapget1 = map.get('name') console.log(mapget1) // lili let mapget2 = map.getIn(['mather','height']) console.log(mapget2)
List 的增删改查
let list = Immutable.List([1,21,10,45,32]) console.log(list) console.log(list.size) // 5 console.log(list._tail) console.log(list._tail.array) // 增 let list1 = list.push(75) console.log(list1) // 删除 let list2 = list.splice(0,1) console.log(list2) // 查询 let list3 = list.toArray() // toArray 只能转换一层 console.log(list3)