由codewars上的一道题目学习ES6的Map

发布时间:2019-08-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了由codewars上的一道题目学习ES6的Map脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

我对ES6数据结构Map的学习

最近在CodeWars上做了一道题目,嗯,我这个渣渣没有做出来,然后看了别人的解决方案Map???

是时候学习一下ES6的Map了。。。。。

以下是原题:(https://www.codewars.com/kata...


Description:

You have a posITive number n consisting of digits. You can do at most one operation: Choosing the index of a digit in the number, remove this digit at that index and insert it back to another place in the number.

Doing so, find the smallest number you can get.

Task:

Return an array or a tuple dePEnding on the language (see "Your test Cases" Haskell) with

1) the smallest number you got
2) the index i of the digit d you took, i as small as possible
3) the index j (as small as possible) where you insert this digit d to have the smallest number.

Example:

smallest(261235) --> [126235, 2, 0]

126235 is the smallest number gotten by taking 1 at index 2 and putting it at index 0

smallest(209917) --> [29917, 0, 1]

[29917, 1, 0] could be a solution too but index i in [29917, 1, 0] is greater than
index i in [29917, 0, 1].

29917 is the smallest number gotten by taking 2 at index 0 and putting it at index 1 which gave 029917 which is the number 29917.

smallest(1000000) --> [1, 0, 6]


以下就是某人的解决方案:

Array.PRototype.move = function(from, to) {
    this.splice(to, 0, this.splice(from, 1)[0]);
    return this;
};

function smallest(n) {
  let iter = `${n}`.length, res = new Map(); //使用ES6的模板字符串还有Map数据结构
  for (let i = 0; i < iter; i++) {
    for (let j = 0; j < iter; j++) {
      let number = `${n}`.split('').move(i, j).join(''); //排列组合???哈哈
      if (!res.has(+number)) res.set(+number, [i, j]); //添加键值对到Map
    }
  }
  let min = Math.min(...res.keys()); //res.keys()得到键名的遍历器,然后扩展运算符转化为数组,然后最小的number
  return [min, ...res.get(min)]; //res.get(min)得到对应键名的键值
}

以下内容来自大神博客:阮一峰ES6入门书籍

认识Map数据结构

JavaScript的对象(Object),本质上是键值对的集合(Hash结构),但是传统上只能用字符串当作键。这给它的使用带来了很大的限制。

Map数据结构类似于对象,也是键值对的集合,但是键的范围不限于字符串,各种类型的值都可以作为键。如果你需要“键值对”的数据结构,Map比Object更合适。

VAR m = new Map();
var o = {p: 'hello world'};

m.set(0, 'connect');
m.get(0); //'connect'

m.has(0); //true
m.delete(o); //true
m.has(o); //false

MaP实例的属性和方法

  • size():返回Map结构的成员总数

操作方法

  • set(key, value):设置对应的键值,然后返回整个Map结构。如果key已经有值,则键值会被更新。

var m = new Map();

m.set("edition", 6)        // 键是字符串
m.set(262, "standard")     // 键是数值
m.set(undefined, "nah")    // 键是undefined

//set方法返回的是Map本身,因此可以采用链式写法。
let map = new Map()
  .set(1, 'a')
  .set(2, 'b')
  .set(3, 'c');
  • get(key):读取key对应的键值,如果找不到key返回undefined

var m = new Map();

var hello = function() {
    console.LOG("hello");
}
m.set(hello, "Hello ES6!") // 键是函数

m.get(hello)  // Hello ES6!
  • has(key):返回一个布尔值,表示某个键是否在Map数据结构中。

  • delete(key):删除某个键,成功返回true;删除失败返回false

  • clear():删除所有成员,没有返回值。

遍历方法

  • keys():返回键名的遍历器

  • values():返回键值的遍历器

  • entries():返回所有成员的遍历器

  • foreach():遍历Map的所有成员

let map = new Map([
  ['F', 'no'],
  ['T',  'yes'],
]);

for (let key of map.keys()) {
  console.log(key);
}
// "F"
// "T"

for (let value of map.values()) {
  console.log(value);
}
// "no"
// "yes"

for (let item of map.entries()) {
  console.log(item[0], item[1]);
}
// "F" "no"
// "T" "yes"

// 或者
for (let [key, value] of map.entries()) {
  console.log(key, value);
}

// 等同于使用Map.entries()
for (let [key, value] of map) {
  console.log(key, value);
}

Map数据结构的转换

使用扩展运算符(...)

let mao = new Map().set(true, 7).set({foo: 3}, ['abc']);
[...mao]; //[ [true, 7], [{foo: 3}, ['abc']] ]

转换为数组结构之后,结合数组的map()方法,filter()方法可以实现Map的遍历和过滤。Map本身没有map和filter方法,但是有一个forEach方法

let map0 = new Map()
  .set(1, 'a')
  .set(2, 'b')
  .set(3, 'c');

let map1 = new Map(
  [...map0].filter(([k, v]) => k < 3)
);
// 产生Map结构 {1 => 'a', 2 => 'b'}

let map2 = new Map(
  [...map0].map(([k, v]) => [k * 2, '_' + v])
    );
// 产生Map结构 {2 => '_a', 4 => '_b', 6 => '_c'}
  • 数组转为Map

new Map([[true, 7], [{foo: 3}, ['abc']]])
// Map {true => 7, Object {foo: 3} => ['abc']}

PS:

下面的例子中,字符串true和布尔值true是两个不同的键。

var m = new Map([
  [true, 'foo'],
  ['true', 'bar']
]);

m.get(true) // 'foo'
m.get('true') // 'bar'

如果对同一个键多次赋值,后面的值将覆盖前面的值。

let map = new Map();

map
.set(1, 'aaa')
.set(1, 'bbb');

map.get(1) // "bbb"

上面代码对键1连续赋值两次,后一次的值覆盖前一次的值。

如果读取一个未知的键,则返回undefined

new Map().get('asfdDFsasadf')
// undefined

注意,只有对同一个对象的引用,Map结构才将其视为同一个键。这一点要非常小心

var map = new Map();

map.set(['a'], 555);
map.get(['a']) // undefined

上面代码的set和get方法,表面是针对同一个键,但实际上这是两个值,内存地址是不一样的,因此get方法无法读取该键,返回undefined。

由上可知,Map的键实际上是跟内存地址绑定的,只要内存地址不一样,就视为两个键。这就解决了同名属性碰撞(clash)的问题,我们扩展别人的库的时候,如果使用对象作为键名,就不用担心自己的属性与原作者的属性同名。

如果Map的键是一个简单类型的值(数字、字符串、布尔值),则只要两个值严格相等,Map将其视为一个键,包括0和-0。另外,虽然NaN不严格相等于自身,但Map将其视为同一个键。

let map = new Map();

map.set(NaN, 123);
map.get(NaN) // 123 这里是同一个键

map.set(-0, 123);
map.get(+0) // 123

脚本宝典总结

以上是脚本宝典为你收集整理的由codewars上的一道题目学习ES6的Map全部内容,希望文章能够帮你解决由codewars上的一道题目学习ES6的Map所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。