首页 > 解决方案 > Es6:无法从类创建对象

问题描述

我正在尝试从“Storage”类创建对象,我可以在其中存储多个键值对(使用 ES6),但它不起作用。

它甚至没有抛出错误,我做错了什么?

这是我的代码:

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)

标签: javascriptclassfrontend

解决方案


抛出的错误是

Uncaught TypeError: Iterator value 0 is not an entry object

在线

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

如果您查看构造函数的文档,则Map需要传递它:

一个数组或其他可迭代对象,其元素是键值对(具有两个元素的数组,例如 [[ 1, 'one' ],[ 2, 'two' ]])。

因此,不要传递具有两个值的数组,而是传递一个包含另一个包含两个值的数组的数组:

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


推荐阅读