我刚开始学习javascript。今天尝试学习地图对象键和值对。但不知怎的,我看到Map的一个非功能方法就是clear()。
我在下面发布的整个代码。虽然已调用map对象clear方法,但line34和line36打印相同的映射对。我哪里错了?我只想清除名为list_的Map对象 这是一个你可以测试并看到怪异的链接:https://codepen.io/KTURKAY/pen/oEpXgb
var list_ = new Map();
var inputkey;
var inputvalue;
var buttonadd;
var buttonclear;
var divlist;
function buttonclearclick(el, ev) {
divlist.innerHTML = '';
console.log(list_);
list_.clear();//I expected, this method should clear it. but indeed it doesn't.?
console.log(list_);
}
function buttonaddclick(c, e) {
list_[inputkey.value] = inputvalue.value;
divlist.innerHTML = "";
for (x in list_) {
let n = document.createElement('div');
n.innerHTML = `${x} = ${list_[x]}`;
divlist.appendChild(n);
}
}
document.body.onload = function(ev) {
inputkey = document.getElementById('inputkey');
inputvalue = document.getElementById('inputvalue');
buttonadd = document.getElementById('buttonadd');
buttonclear = document.getElementById('buttonclear');
divlist = document.getElementById('divlist');
buttonadd.addEventListener('click', buttonaddclick);
buttonclear.addEventListener('click', buttonclearclick);
}

<form>
KEY:
<input type="text" id="inputkey" /> VALUE:
<input type="text" id="inputvalue" />
<input type="button" value="ADD" id="buttonadd" />
<input type="button" value="CLEAR" id="buttonclear" />
</form>
<div id="divlist">
NO DATA
</div>
&#13;
答案 0 :(得分:1)
问题在于:
list_[inputkey.value] = inputvalue.value;
您需要使用get
和set
来使用Google地图:
list_.set(inputkey.value, inputvalue.value);
调用clear()
会删除内部Maps Hashmap中的所有键/值,但不会清除对象属性。如果你使用第一种设置属性的方法,你实际上并不需要Map,但你可以使用普通对象。
答案 1 :(得分:1)
一些问题:
.get
方法。for ... of
代替for ... in
在此代码段中查看正确运行的更新脚本。评论表明更正:
var list_ = new Map();
var inputkey;
var inputvalue;
var buttonadd;
var buttonclear;
var divlist;
function buttonclearclick(el, ev) {
divlist.innerHTML = '';
console.log('before: ' + list_.size); // To make it work in this snippet
list_.clear();
console.log('after: ' + list_.size); // To make it work in this snippet
}
function buttonaddclick(c, e) {
list_.set(inputkey.value, inputvalue.value); // Use set
divlist.innerHTML = "";
for (const [key, value] of list_) { // Get entries using `of`
const n = document.createElement('div');
n.textContent = `${key} = ${value}`; // Use pair coming from iterator
divlist.appendChild(n);
}
}
document.body.onload = function (ev) {
inputkey = document.getElementById('inputkey');
inputvalue = document.getElementById('inputvalue');
buttonadd = document.getElementById('buttonadd');
buttonclear = document.getElementById('buttonclear');
divlist = document.getElementById('divlist');
buttonadd.addEventListener('click', buttonaddclick);
buttonclear.addEventListener('click', buttonclearclick);
}
&#13;
<form>
KEY:
<input type="text" id="inputkey" /> VALUE:
<input type="text" id="inputvalue" />
<input type="button" value="ADD" id="buttonadd" />
<input type="button" value="CLEAR" id="buttonclear" />
</form>
<div id="divlist">
NO DATA
</div>
&#13;