数组中Javascript对象的解构

数组中Javascript对象的解构,javascript,Javascript,我有一个对象数组: var myArrayOfObjects = [ {Attempt: 1, level: 8, Score: 10}, {Attempt: 2, level: 9, Score: 8}, {Attempt: 3, level: 3, Score: 7}, {Attempt: 4, level: 4, Score: 9},

我有一个对象数组:

var myArrayOfObjects = [
                {Attempt: 1, level: 8, Score: 10},
                {Attempt: 2, level: 9, Score: 8},
                {Attempt: 3, level: 3, Score: 7},
                {Attempt: 4, level: 4, Score: 9},
                {Attempt: 5, level: 3, Score: 5},
                {Attempt: 6, level: 1, Score: 8}];


  console.log(myArrayOfObjects);
尝试可以是无限的。级别和分数都是从1到10的数字。但在这个问题上,分数对我来说无关紧要

我想弄清楚的是,记录每次尝试的(最佳)方式,一个级别以前是否尝试过,下面尝试过的级别和上面尝试过的级别

因此,我期望的输出是:

//[{Attempt: 1, At this level: 0, Above this level: 0, Below this level: 0}; 
//{Attempt: 2, At this level: 0, Above this level: 0, Below this level: 1}; 
//{Attempt: 3, At this level: 0, Above this level: 2, Below this level: 0};
//{Attempt: 4, At this level: 0, Above this level: 2, Below this level: 1};
//{Attempt: 5, At this level: 1, Above this level: 3, Below this level: 0};
//{Attempt: 6, At this level: 0, Above this level: 5, Below this level: 0}];

关于如何使用纯Javascript实现这一点,有什么想法吗?

请看一下他的代码。它可能对您有帮助,也可能没有帮助:)

var级别=[];
//创建类似CerateTempt的尝试(级别编号、分数)
createtrunt(0,10);
createtrunt(0,13);
createtrunt(0,14);
createtrunt(0,15);
//记录0级的所有尝试
for(设i=0;i最后得分”)
else console.log(“在:+levels[0]之后的分数。尝试[i+1]。分数);
如果(!levels[0].truments[i-1])console.log(“无之前的分数->第一个分数”);
else console.log(“之前的分数:+级别[0]。尝试[i-1]。分数”);
}
函数CreateTreant(lvl,分数){
if(类型(级别[lvl])=“未定义”){
级别[lvl]={};
级别[lvl]。尝试次数=[];
}
级别[lvl].truments.push({score:score});

}
一个简单的循环和一个数组可以跟踪每个级别的尝试次数:

function sum(arr) { return arr.reduce((a, b) => a + b, 0); }

let attempts = [];
for (const [index, obj] of myArrayOfObjects.entries()) {
    console.assert(index + 1 == obj.Attempt); // ensure input is sorted by attempt
    console.log(`Attempt ${obj.Attempt},
    At this level: ${attempts[obj.level] || 0},
    Above this level: ${sum(attempts.slice(obj.level+1))},
    Below this level: ${sum(attempts.slice(0, obj.level))}`); 
    attempts[obj.level] = (attempts[obj.level] || 0) + 1; // increase count for this level
}

您还可以将结果放入新对象和数组中。

高于/低于
级别是什么?您的
myArrayOfObjects
是一个级别吗?最终将是其他级别的每个用户的数组。您从哪里获得缺少的数据?顺便问一下,为什么标题称为“解构”?这不是更像一个“如何构建”吗?我想剥离或拆除我的问题,然后重建它。因此,对我来说,“解构”是合适的。你能给我一个
console.log(“Text${variable}”)
以前从未见过的参考吗?非常感谢Bergi。这是一个很好的解决方案。@Elias这是一个很好的解决方案,但对于答案的细节来说并不重要。谢谢你的帮助。@TerenceE.Uttley请快速浏览一下代码:)