html写一个函数:counter。参数:一个数字数组。返回:给定数组中负元素、零和大于零的值的数目。注意:函数中必须使用switch语句。
时间: 2023-05-30 13:03:55 浏览: 41
<html>
<head>
<script>
function counter(arr) {
let negativeCount = 0;
let zeroCount = 0;
let positiveCount = 0;
for (let i = 0; i < arr.length; i++) {
switch (Math.sign(arr[i])) {
case -1:
negativeCount++;
break;
case 0:
zeroCount++;
break;
case 1:
positiveCount++;
break;
}
}
return {
negative: negativeCount,
zero: zeroCount,
positive: positiveCount,
};
}
let myArray = [-1, 0, 1, 2, -3, 4, 0, -5];
let result = counter(myArray);
console.log(result);
</script>
</head>
<body></body>
</html>