HarmonyOS 鸿蒙Next API11,如何获取数组最大值

发布于 1周前 作者 ionicwang 来自 鸿蒙OS

HarmonyOS 鸿蒙Next API11,如何获取数组最大值

API11,怎么获取数组最大值~报错信息说我类型没定义,但是没看懂我哪里没定义

Argument of type ‘number | undefined’ is not assignable to parameter of type ‘number’. Type ‘undefined’ is not assignable to type ‘number’

cke_51261.png


更多关于HarmonyOS 鸿蒙Next API11,如何获取数组最大值的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

6 回复

同样代码偶的IDE没有报错,编译运行正常可得到结果也正常。不过你可试试以下两种转换看有没有帮助:

this.maxValue = Math.max(...this.screenList.map((item: chartData) => item.value)) as number;
this.minValue = Math.min(...this.screenList.map((item: chartData) => item.value as number));

更多关于HarmonyOS 鸿蒙Next API11,如何获取数组最大值的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


确实,强转一下类型就好啦~谢谢,

Argument of type ‘number | undefined’ is not assignable to parameter of type ‘number’. Type ‘undefined’ is not assignable to type ‘number’

传递给 number 类型参数的值可能为 number(数字)或 undefined(未定义)。如果参数数组中有 undefined (未定义), 则编译时会报错。函数不能够处理 undefined(未定义)。

试试看这样。过滤掉undefined。

this.maxValue = Math.max(...this.screenList.map((item: chartData) => item.value).filter(value => value !== undefined));
this.minValue = Math.min(...this.screenList.map((item: chartData) => item.value).filter(value => value !== undefined));

通过for循环可以得到数组中的最大值,但是想用map的方式,该如何实现

在HarmonyOS鸿蒙Next API11中,获取数组最大值可以通过使用Math.max函数结合展开运算符...来实现。假设你有一个数组arr,你可以通过以下代码获取数组中的最大值:

let arr = [1, 2, 3, 4, 5];
let maxValue = Math.max(...arr);

Math.max函数用于返回一组数中的最大值,而展开运算符...将数组中的元素展开为单独的参数传递给Math.max。这样,Math.max就可以直接处理数组中的元素并返回最大值。

如果数组为空,Math.max将返回-Infinity。因此,在实际使用中,建议先检查数组是否为空,以避免意外结果。

if (arr.length > 0) {
    let maxValue = Math.max(...arr);
} else {
    console.log("数组为空");
}

这种方法简洁高效,适用于大多数场景。

在HarmonyOS(鸿蒙)Next API 11中,你可以通过遍历数组来获取最大值。以下是一个简单的示例代码:

public int getMaxValue(int[] array) {
    if (array == null || array.length == 0) {
        throw new IllegalArgumentException("Array is empty or null");
    }
    int max = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] > max) {
            max = array[i];
        }
    }
    return max;
}

这个方法首先检查数组是否为空或为null,然后通过遍历数组来找到最大值并返回。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!