Javascript 对数组中的对象进行排序
我的变量Javascript 对数组中的对象进行排序,javascript,node.js,Javascript,Node.js,我的变量options pergunta中有一个数组options需要排序的对象: 我试过这样的方法: optionsPergunta.sort(this.sorteiaArray) sorteiaArray(){ return Math.random() < Math.random() } 当我返回结果并在postman中进行测试时,我得到了以下结果: [ { "id": 6, "book_unit_question_id": 2, "descrip
options pergunta
中有一个数组options
需要排序的对象:
我试过这样的方法:
optionsPergunta.sort(this.sorteiaArray)
sorteiaArray(){
return Math.random() < Math.random()
}
当我返回结果并在postman中进行测试时,我得到了以下结果:
[
{
"id": 6,
"book_unit_question_id": 2,
"description": "get",
"image_sound": null,
"correct": true,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 16:06:27",
"updated_at": "2019-12-27 16:06:27"
},
{
"id": 9,
"book_unit_question_id": 2,
"description": "stay",
"image_sound": null,
"correct": false,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 16:06:45",
"updated_at": "2019-12-27 16:06:45"
},
{
"id": 5,
"book_unit_question_id": 2,
"description": "are",
"image_sound": null,
"correct": false,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 16:06:21",
"updated_at": "2019-12-27 16:06:33"
},
{
"id": 8,
"book_unit_question_id": 2,
"description": "move",
"image_sound": null,
"correct": false,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 16:06:43",
"updated_at": "2019-12-27 16:06:43"
}
]
长话短说
options pergunta
指的是sort()
来自的对象,这意味着您需要对数组调用sort()
。另一件事是,sortiaarray
前面没有函数,因此解释器认为它应该是函数调用
const options pergunta={
“选择”:[
{
“id”:6,
“图书单元问题编号”:2,
“说明”:“获取”,
“图像声音”:空,
“正确”:正确,
“状态”:假,
“用户id”:1,
“创建时间”:“2019-12-27 16:06:27”,
“更新时间”:“2019-12-27 16:06:27”
},
{
“id”:5,
“图书单元问题编号”:2,
“说明”:“是”,
“图像声音”:空,
“正确”:错误,
“状态”:假,
“用户id”:1,
“创建时间”:“2019-12-27 16:06:21”,
“更新时间”:“2019-12-27 16:06:33”
},
{
“id”:7,
“图书单元问题编号”:2,
“说明”:“转到”,
“图像声音”:空,
“正确”:错误,
“状态”:假,
“用户id”:1,
“创建时间”:“2019-12-27 16:06:39”,
“更新时间”:“2019-12-27 16:06:39”
},
{
“id”:8,
“图书单元问题编号”:2,
“说明”:“移动”,
“图像声音”:空,
“正确”:错误,
“状态”:假,
“用户id”:1,
“创建时间”:“2019-12-27 16:06:43”,
“更新时间”:“2019-12-27 16:06:43”
}
]
}
函数数组(){
返回Math.random() console.log(optionsPergunta.options.sort(sortiaarray))
显然,您不需要对数组进行排序,只需要将其洗牌
通过使用返回随机值的比较函数对数组进行排序来洗牌不是一个好主意。对于某些排序算法,它会导致一个不能保证结束的循环
如果需要洗牌数组,有一种更好(可能更快)的方法:从数组中随机选取一个项目,将其从数组中移除,并将其附加到新数组(洗牌数组)。代码可能如下所示:
// Create a new array to not change the original
let source = optionsPergunta.slice();
// Store the shuffled items here
let shuffled = [];
while (source.length) {
let index = Math.floor(Math.random() * Math.floor(source.length));
let items = source.splice(index, 1);
shuffled.push(items[0]);
}
您需要对选项pergunta进行排序。options
@Barmar options pergunta是“options”对象内容options pergunta.options未定义排序标准是什么?显然,您不需要对数组进行排序,只需要将其洗牌。通过使用返回随机值的排序函数进行排序来洗牌不是一个好主意。对于某些排序算法,它会导致一个不能保证结束的循环。
// Create a new array to not change the original
let source = optionsPergunta.slice();
// Store the shuffled items here
let shuffled = [];
while (source.length) {
let index = Math.floor(Math.random() * Math.floor(source.length));
let items = source.splice(index, 1);
shuffled.push(items[0]);
}