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)
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With