gpt4 book ai didi

javascript - 在 javascript 中使用 map 计算字符串值,返回 NaN

转载 作者:行者123 更新时间:2023-11-30 05:31:35 26 4
gpt4 key购买 nike

我正在尝试使用映射来计算数组中的重复字符串数,我的代码:

var map = {};
var myarray = ["John", "John", "John", "Doe", "Doe", "Smith",
"John", "Doe", "Joe"];

for (var a = 0; a < myarray.length; a++) {
if (map[myarray[a]] !== null) {
map[myarray[a]] += 1;
} else {
map[myarray[a]] = 1;
}
}

但是当我执行 console.log(map); 它返回

Object {John: NaN, Doe: NaN, Smith: NaN, Joe: NaN}

为什么是NaN?我想要这样的结果:

John :4, Doe: 3, Smith: 1, Joe: 1

我该怎么办?提前谢谢你。

最佳答案

map[myarray[a]] !==null 当字段为 undefined 时返回 true,这是第一次遇到新值时的情况。

应该是:

map[myarray[a]] !== undefined

map[myarray[a]] != null
// undefined == null

关于javascript - 在 javascript 中使用 map 计算字符串值,返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26613078/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com