ES6:无法从类创建对象

K_d*_*dev 4 javascript frontend class

我正在尝试从“存储”类创建对象,在该类中我可以在地图中存储多个键值(使用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)
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 6

引发的错误是

未捕获的TypeError:迭代器值0不是入口对象

在行

this.map = new Map([pKey, pValue]);
Run Code Online (Sandbox Code Playgroud)

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

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

因此,与其传递带有两个值的数组,不如传递一个包含另一个包含两个值的数组的数组:

this.map = new Map([[pKey, pValue]]);
Run Code Online (Sandbox Code Playgroud)

this.map = new Map([pKey, pValue]);
Run Code Online (Sandbox Code Playgroud)