admin管理员组

文章数量:1279118

I am trying to learn about ES6 Map data structures and am having difficulty understanding some of their behaviour. I would like to create a Map with an Array as a value and append (push) new values onto the current value of the Map. For example:

let m = new Map()

m.set(1, []) // []

m.set(1, m.get(1).push(2)) // [[1, 1]]

I am confused as to why I do not get [2] as the value of m.get(1) above. How can I append values to the array in my map?

I am trying to learn about ES6 Map data structures and am having difficulty understanding some of their behaviour. I would like to create a Map with an Array as a value and append (push) new values onto the current value of the Map. For example:

let m = new Map()

m.set(1, []) // []

m.set(1, m.get(1).push(2)) // [[1, 1]]

I am confused as to why I do not get [2] as the value of m.get(1) above. How can I append values to the array in my map?

Share Improve this question asked Jan 4, 2019 at 15:06 turtleturtle 8,09321 gold badges72 silver badges103 bronze badges 1
  • 1 The .push() method returns the length of the array after modification, not the array itself. – Pointy Commented Jan 4, 2019 at 15:09
Add a ment  | 

5 Answers 5

Reset to default 5

That's because the method push returns the size of the array after the insertion.

You can change your code to the following to append to an array:

m.get(1).push(2);

And it'll update the value in the map, there's no need to try to re-set the value again as the value is passed back as reference.

The best way to define a Map according to your need is to explicitly tell the Map, what kind of data you want to deal with.

in your case you want values in an array, we could get using a "string id" for example

In this case you will have this :

let map = new Map<String, Array<any>>

Then you can create items like map["key"] = ["lol", 1, null]

There is two thing. First as @Adriani6 said the push method do not returns a pointer to the array but the size of the array.

Secondly, you do not need to do an other m.set, because your push will affect directly the array behind the reference returned by m.get

function displayMap(m) {
  m.forEach(function(val, key) {
    console.log(key + " => " + val);
  });
}

let m = new Map();

m.set(1, []);

displayMap(m);

m.get(1).push(20);

displayMap(m);

It fails, because the return of push() is the size of the array after push.

  1. You can push the content after doing a get().

    m.get(1).push(2);

  2. If you want to test set() then write a a self executable function like this:

let m = new Map()

m.set(1, []) // []

console.log(m.get(1))

m.set(1, (() => {m.get(1).push(2);return m.get(1);})());

console.log(m.get(1))

Here's a working example of what you are trying to do (open console)

Have a look here. As you can see the push method returns the new length of the array you just mutated, hence your result.

本文标签: javascriptHow to append values to ES6 MapStack Overflow