Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Es6: can't create objects from class

I'm trying to create objects from class "Storage" where i can store in a map multiple key-values (using ES6), but its not working.

Its not even throwing errors, what am i doing wrong?

Here is my code:

class Storage
{
    constructor( pKey, pValue )
    {
        this.key = pKey;
        this.value = pValue;
        this.map = new Map( [ pKey, pValue ] );
        console.log( this.map );//current output: (nothing)
    }


    set( pKey, pValue )
    {
        this.map.set( pKey, pValue );
    }

    get( pKey )
    {
        var result = this.map.get( pKey );
        return result;
    }

}

var myStorage = new Storage( "0", "test" );

console.log( myStorage.get( "0" ) );//espected output: "test" | current output: (nothing)
like image 270
K_dev Avatar asked Aug 22 '18 00:08

K_dev


1 Answers

The error thrown is

Uncaught TypeError: Iterator value 0 is not an entry object

at the line

this.map = new Map([pKey, pValue]);

If you look at the documentation for the Map constructor, you need to pass it:

An Array or other iterable object whose elements are key-value pairs (arrays with two elements, e.g. [[ 1, 'one' ],[ 2, 'two' ]]).

So, instead of passing an array with two values, pass an array which contains another array which contains two values:

this.map = new Map([[pKey, pValue]]);

class Storage {
  constructor(pKey, pValue) {
    this.key = pKey;
    this.value = pValue;
    this.map = new Map([[pKey, pValue]]);
  }


  set(pKey, pValue) {
    this.map.set(pKey, pValue);
  }

  get(pKey) {
    var result = this.map.get(pKey);
    return result;
  }

}

var myStorage = new Storage("0", "test");

console.log(myStorage.get("0"));
like image 103
CertainPerformance Avatar answered Oct 10 '22 20:10

CertainPerformance