使用用户提示()的二维数组?

问题描述 投票:0回答:1

var playerinfo = [
    ["Anisul", 122],
    ["Rahim", 433],
    ["Kabir Singh", 788],
    ["Munna", 56],
    ["Rasel", 120]
];

function highestRunScorer(playerinfo) {
    var highScorer = playerinfo[0][0];
    var highScore = playerinfo[0][1];
    for (var x = 1; x < playerinfo.length; x++) {
        if (highScore < playerinfo[x][1]) {
            highScore = playerinfo[x][1];
            highScorer = playerinfo[x][0];
        }
    }
    return highScorer;
}

var names = highestRunScorer(playerinfo);
console.log(names);

现在我想知道如何利用用户输入来创建这个二维数组并以现实世界的方式解决这个问题。

我尝试搜索如何使用提示创建二维数组。但到目前为止还没有运气。因此在这里发帖。顺便说一句,我是 Javascript 新手。

javascript arrays multidimensional-array
1个回答
0
投票

您可以使用以下代码来完成:

function findHighestValueInArray() {
    // Taking input for the number of rows and columns
    const numRows = parseInt(prompt("Enter the number of rows:"));
    const numCols = parseInt(prompt("Enter the number of columns:"));

    // Initializing a two-dimensional array
    const matrix = [];

    // Taking input for each element in the array
    for (let i = 0; i < numRows; i++) {
        const row = [];
        for (let j = 0; j < numCols; j++) {
            const userInput = prompt(`Enter element at position (${i + 1},${j + 1}):`);
            // Parsing the input to check if it's an integer
            const element = parseInt(userInput);

            // Adding the element to the row
            row.push(isNaN(element) ? userInput : element);
        }
        // Adding the row to the matrix
        matrix.push(row);
    }

    // Finding the highest value in the array
    let highestValue = Number.NEGATIVE_INFINITY;

    for (let row = 0; row < matrix.length; row++) {
        for (let col = 0; col < matrix[row].length; col++) {
            // Check if the element is an integer
            if (typeof matrix[row][col] === 'number') {
                // Update highestValue if the current element is greater
                highestValue = Math.max(highestValue, matrix[row][col]);
            }
        }
    }

    // Returning the highest value
    return highestValue;
}

// Example usage:
const result = findHighestValueInArray();
console.log('The highest value is:', result);

© www.soinside.com 2019 - 2024. All rights reserved.