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