由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数据构造的转换

  • 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
    原文作者:luckyzv
    原文地址: https://segmentfault.com/a/1190000008829770
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞