您的位置:首页 > 编程语言

优化if-else代码

2018-11-08 14:41 190 查看

//例子

var mMap = new Map([
[162,function(h,a){console.log("he height is" + h + " ,he age is" + a)}],
[174,function(h,a){console.log("he height is" + h + " ,he age is" + a)}],
[198,function(h,a){console.log("he height is" + h + " ,he age is" + a)}],
])
var height = 150, age = 12;
mMap.get(height  + age)(height,age)  //he height is150 ,he age is12

//正则
var mMap = new Map([
[/^\d{2,5}$/,function(h,a){console.log("位数大于2且小于5")}],
[/^\d{5,10}$/,function(h,a){console.log("位数大于5且小于10")}],
])
var arr = [...mMap].filter(([k,v])=>(k.test(`123`)))
arr.forEach(([k,v])=>v.call(this))    //位数大于2且小于5

//对Map数据结构做简要介绍
定义:

Map 对象保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。
语法:

new Map([iterable]) Iterable 可以是一个数组或者其他 iterable 对象,其元素或为键值对,或为两个元素的数组。 每个键值对都会添加到新的 Map。null 会被当做 undefined。
方法:

Map.prototype.get(key) 返回键对应的值,如果不存在,则返回undefined。
Map.prototype.has(key) 返回一个布尔值,表示Map实例是否包含键对应的值。
Map.prototype.set(key, value) 设置Map对象中键的值。返回该Map对象。
对于Map数据结构来说,不支持 = 号的赋值~~~~~~~

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: