javascript - 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)
解决方案
抛出的错误是
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"));
推荐阅读
- c# - 如何通过此功能使用更少的内存?
- javascript - 如何在javascript中设置innerHTML?
- powershell - Electron - jQuery 和 Powershell
- elasticsearch - 是否可以通过更改 elasticsearch data/nodes/0/indices/{index_id}/index 文件夹的任何二进制文件来更改文档?
- java - HHH000100:故障安全清理(集合)
- database - 关系代数企业约束
- swift - 如何使 macOS 菜单文本动态化?
- python - Django collectstatic --no 输入是而不是否
- azure-active-directory - 使用 Graph API 列出虚拟机的权限
- python - 用于特定颜色部分提取的 Numpy