具有名称数组。其中一些重复出现,映射不正确,并且在迭代值时遇到一些问题
var arrayOfWords = ['Doug', 'Cait', 'Fred', 'Cait', 'Piper', 'Richard', 'Fred', 'Emet', 'Hugo', 'Fred', 'Daisy', 'Bart', 'Fred', 'Cait', 'Cait'];
var howMuchEachElementRepeatsInArray = new Map();
var counter = 0;
console.log("Array of strings: " + arrayOfWords);
for (let i = 0; i < arrayOfWords.length; i++) {
if (howMuchEachElementRepeatsInArray.has(arrayOfWords[i])) {
howMuchEachElementRepeatsInArray.delete(counter);
counter = counter + 1;
howMuchEachElementRepeatsInArray.set(arrayOfWords[i], counter);
} else if (!howMuchEachElementRepeatsInArray.has(arrayOfWords[i])) {
counter = 1;
howMuchEachElementRepeatsInArray.set(arrayOfWords[i], counter);
}
}
console.log("How much each element repeats in map: ");
for (let keyvalue of howMuchEachElementRepeatsInArray) {
console.log(keyvalue);
}
我希望得到输出:
Array of strings: Doug,Cait,Fred,Cait,Piper,Richard,Fred,Emet,Hugo,Fred,Daisy,Bart,Fred,Cait,Cait
How much each element repeats in map:
[ 'Doug', 1 ]
[ 'Cait', 4 ]
[ 'Fred', 4 ]
[ 'Piper', 1 ]
[ 'Richard', 1 ]
[ 'Emet', 1 ]
[ 'Hugo', 1 ]
[ 'Daisy', 1 ]
[ 'Bart', 1 ]
但是得到:
Array of strings: Doug,Cait,Fred,Cait,Piper,Richard,Fred,Emet,Hugo,Fred,Daisy,Bart,Fred,Cait,Cait
How much each element repeats in map:
[ 'Doug', 1 ]
[ 'Cait', 4 ]
[ 'Fred', 2 ]
[ 'Piper', 1 ]
[ 'Richard', 1 ]
[ 'Emet', 1 ]
[ 'Hugo', 1 ]
[ 'Daisy', 1 ]
[ 'Bart', 1 ]
不完全理解为什么counter不正确计算名称[Fred]的迭代次数