如何返回数组中 n 个最大值的总和?

发布于 2023-02-15 08:57:11
import React from 'react';
import ReactDOM from 'react-dom';
import { useState } from 'react';

const Dice = () => {
    const [dice, setDice] = useState([1, 1, 2, 2]);

    function rollDice() {
        return Array.from({length: 4}, () => Math.floor(Math.random() * 6) + 1);
    }


    const handleClick = () => {
        setDice(rollDice());
    }

    const rolls = dice.map(die => <span> {die} </span> );

    const stat = dice.splice(Math.min(...dice)).reduce(function(a, b) {
        return a + b;
    });

    return (
        <>
            <button onClick={handleClick}>Roll for stats</button>

            <div>
                Your rolls are: {rolls}
            </div>
            
            <div>
                Your stat is: {stat}
            </div>
        </>
    );
}

export default Dice;

if (document.getElementById('dice')) {
    ReactDOM.render(<Dice />, document.getElementById('dice'));
}

所以我正在制作在线 DnD,我正在测试掷骰子的统计数据,前几次迭代运行良好,然后它返回了错误数字的总和,它“随机”删除了我需要的数字并返回了错误的总和。我在离开代码世界一段时间后正在这样做,所以如果这很愚蠢,我很抱歉,但我真的无法弄清楚问题是什么。

查看更多

1楼回答 2023-02-14

您可以为此使用 reduce

function sumOfNHighestValues(arr: number[], n: number): number {
  const sortedArr = arr.sort((a, b) => b - a); // sort the array in descending order
  const slicedArr = sortedArr.slice(0, n); // slice the first n elements
  const sum = slicedArr.reduce((total, num) => total + num, 0); // sum the sliced elements
  return sum;
}

// example usage
const arr = [5, 2, 8, 3, 9, 4];
const n = 3;
const result = sumOfNHighestValues(arr, n);
console.log(result); // output: 21 (sum of 9, 8, and 5)
2楼回答 2023-02-11

这样就可以了,将 stat 更改为函数并在 dice 数组的副本上运行 splice 方法:

const stat = () => {
    let smallestRoll = Math.min(...dice)
    let indexOfSmallest = dice.indexOf(smallestRoll)
    let diceCopy = [...dice]

    diceCopy.splice(indexOfSmallest, 1)

    let sum = diceCopy.reduce(function(a, b) {
        return a + b;
    });

    return sum;
}

并将其作为函数返回:

return (
    <>
        <div>
            Your stat is: {stat()}
        </div>
    </>
);

谢谢你的帮助!

3楼回答 2023-02-12

你可以尝试 es6 语法,扩展运算符(...)

var arr = [22,13,6,55,30];
console.log(Math.max(...arr)); // 55
请登录后再发布答案,点击登录