随机数组排序方法 Javascript

Random Array Sort Method Javascript

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

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 应该 return 一个数组,其中最后 3 个对象参数以随机顺序排列,但它显示“function randomOrder()”。是方法声明还是调用错误?

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)