随机数组排序方法Javascript [关闭]

Posted

技术标签:

【中文标题】随机数组排序方法Javascript [关闭]【英文标题】:Random Array Sort Method Javascript [closed] 【发布时间】:2022-01-17 12:20:21 【问题描述】:

目前我正在构建一个测验应用程序,它以随机顺序显示一个带有正确和 3 个错误答案的动词。 类是:

class IrregularVerb 
    constructor(verb, right, wrongFirst, wrongSecond, wrongThird) 
        this._verb = verb;
        this._right = right;
        this._wrong = [wrongFirst, wrongSecond, wrongThird];
    

    randomOrder() 
        return this._wrong.sort(0.5 - Math.random());
    


const irregularVerbList = [
    new IrregularVerb("read", "read", "rode", "ride", "ridden"),
    new IrregularVerb("go", "went", "gone", "got", "god")
]


const randomWrongAnswer = irregularVerbList[randomNumber].randomOrder;

randomWrongAnswer 应该以随机顺序返回一个包含最后 3 个对象参数的数组,但它显示“函数 randomOrder()”。方法声明或其调用是否错误?

【问题讨论】:

您必须调用该方法。括号不见了。您只是分配了函数对象而不是函数调用的结果。 【参考方案1】:

需要解决的 3 件事

class IrregularVerb 
  constructor(verb, right, wrongFirst, wrongSecond, wrongThird) 
    this._verb = verb;
    this._right = right;
    this._wrong = [wrongFirst, wrongSecond, wrongThird];
  

  randomOrder() 
    return this._wrong.sort(()=>0.5 - Math.random());
    //                      ^^^^  Need these parentheses and fat arrow
    //                            to make it a function
  


const irregularVerbList = [
  new IrregularVerb("read", "read", "rode", "ride", "ridden"),
  new IrregularVerb("go", "went", "gone", "got", "god")
]


const randomNumber = Math.floor(Math.random()*2)
// Need this so that randomNumber is not undefined

const randomWrongAnswer = irregularVerbList[randomNumber].randomOrder();
//                           Need this to actually call the function ^^
console.log(randomWrongAnswer)

【讨论】:

感谢您的帮助,语法对我来说很新。祝您有美好的一天!

以上是关于随机数组排序方法Javascript [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

javascript 按随机顺序对数组进行排序

javascript实现数组随机排序和去重

关于JavaScript的数组随机排序

面试题:数组随机排列

对 50 000 个对象的数组进行排序 - Javascript [关闭]

如何使用相同的随机排序对两个数组进行排序