【发布时间】:2021-01-17 00:47:12
【问题描述】:
返回数组模式值的函数适用于除一个之外的每个测试。当我通过函数传递以下数组时,我得到一个 TypeError。我发现它与传递数组中的数字0有关,但我不知道为什么,也不知道如何解决问题。这就是我的 mode 函数和 typeerror 函数的样子。
function mode (arr) {
throwErrors(arr)
const numberOccurence = {}
const mostOccurent = []
for (const numberValues of arr) {
if (numberOccurence[numberValues]) {
numberOccurence[numberValues] += 1
} else {
numberOccurence[numberValues] = 1
}
}
let timesOccured = Object.values(numberOccurence)
let numbersSorted = timesOccured.sort((a, b) => b - a)
for (const keys of Object.keys(numberOccurence)) {
if (numberOccurence[keys] === numbersSorted[0]) {
mostOccurent.push(Number(keys))
}
}
return mostOccurent.sort((a, b) => a - b)
}
function throwErrors (functionParameter) {
if (!Array.isArray(functionParameter)) {
throw new TypeError('The passed argument is not an array.')
} else if (functionParameter.length === 0) {
throw new Error('The passed array contains no elements.')
} else if (!functionParameter.every(function checkIfNumber (elements) {
if ((typeof elements == 'number')){
return elements
}
})) {
throw new TypeError('The passed array may only contain valid numbers.')
}
}
如果我将 [3, 5, 2, -5, 9, 2, -5, 5, 10, 4, 1, 0, -1, 9, 0] 传递给函数,我会得到 TypeError: "The传递的数组可能只包含有效数字”,但我希望得到 [-5, 0, 2, 5, 9]
【问题讨论】:
-
那是函数的作用?
标签: javascript arrays typeerror mode