设计一个名为Location的类,定位二维数组中的最大值及其位置。这个类包括属性row(行下标)、column(列下标)和maxValue(最大值)。

这篇博客介绍了一个JavaScript函数locateLargest,用于在二维数组中查找最大值及其对应的行和列索引。函数创建了一个Location对象,存储最大值、行和列信息,并在找到更大值时更新对象。最后,通过Location对象的show方法展示结果。示例中,函数成功地在给定的二维数组中找到了最大值和其位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写函数locateLargest(arr),返回一个Location的对象

(对象中包含了二维数组的最大值、最大值的行下标和列下标):

class Location {
    constructor() {
        this.row = 0;
        this.column = 0 ;
        this.maxValue = arr[0][0];
    };

  
    show(){
        console.log('行下标row:',this.row);
        console.log('列下标row:',this.column);
        console.log('最大值:',this.maxValue);
    }



};
function locateLargest(arr){
    //创建Location类的对象,并假设第一项为最大值
    let max_locate = new Location(0,0,arr[0][0]);

    for (let i = 0; i < arr.length; i++) {//遍历二位数组
        for (let j = 0; j < arr[i].length; j++) {
            if (max_locate.maxValue < arr[i][j]) {
                max_locate.maxValue = arr[i][j];

                max_locate.row = i;
                max_locate.column = j;
            };

        };
    };

    return max_locate;//将对象返回给该函数
}

let arr = [[23, 34, 45, 56], [12, 15, 67, 8], [11, 22, 33, 66]];
let test = locateLargest(arr);//调用函数,返回一个Location对象
//使用对象的方法
test.show();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值