javascript - Es6 : can't create objects from class

标签 javascript class frontend

我正在尝试从类“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)

最佳答案

抛出的错误是

Uncaught TypeError: Iterator value 0 is not an entry object

在线

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

如果您查看 documentation对于 Map 构造函数,您需要传递它:

An Array or other iterable object whose elements are key-value pairs (arrays with two elements, e.g. [[ 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"));

关于javascript - Es6 : can't create objects from class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51958509/

相关文章:

javascript - 有没有办法按数据类型查找所有元素

javascript - 使用 htmlunit 抓取 javascript - "You are currently browsing with JavaScript turned off"

javascript - 所有预加载链接的 Next.js 404 错误

Java - 当导入到主类中时如何使用方法中的变量

javascript - 如何在JS es6类中实现多个方法?

javascript - 哪种方式最适合 React Native 中的条件渲染?

javascript - Angular - 当鼠标不在按钮上时,在按钮 mouseup 上实现事件处理程序

javascript - 从链接获取 YouTube ID 并将其缩略图添加为背景图像(使用 jQuery)

javascript - Next-auth logIn() 在使用 Credentials provider 时卡在/api/auth/providers

c# - XNA - 当前上下文中不存在名称 'ball'