最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Es6: can't create objects from class - Stack Overflow

programmeradmin2浏览0评论

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)

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)
Share Improve this question edited Aug 22, 2018 at 0:54 K_dev asked Aug 22, 2018 at 0:50 K_devK_dev 3471 gold badge2 silver badges9 bronze badges 1
  • 1 The error in Firefox is TypeError: iterable for Map should have array-like objects”. – Sebastian Simon Commented Aug 22, 2018 at 0:54
Add a comment  | 

1 Answer 1

Reset to default 19

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"));

发布评论

评论列表(0)

  1. 暂无评论