我是 javascript 新手,正在尝试通过玩具示例学习一些基础知识。
假设我有一个包含六个人数据的数组。
const myArray = [
{"id": 1, "value": 75, "friends": 3},
{"id": 2, "value": 40, "friends": 4},
{"id": 3, "value": 60, "friends": 5},
{"id": 4, "value": 62, "friends": 6},
{"id": 5, "value": 55, "friends": 1},
{"id": 6, "value": 33, "friends": 2}
];
该数组列出了每个人的id
, value
,以及他们是谁friends
和。例如,人物 1 是人物 3 的朋友,人物 3 是人物 5 的朋友,依此类推。
现在我想根据每个人的价值来操纵谁与谁成为朋友。这是我想要实现的逻辑(可能在 for 循环中):
IF人的价值在于lowest or the 第二低数组中的值,THEN添加此人的 idhighest数组中的值给他们的朋友。
所以在这种情况下我想要的输出是:
const myArray = [
{"id": 1, "value": 75, "friends": 3},
{"id": 2, "value": 40, "friends": [4, 1]},
{"id": 3, "value": 60, "friends": 5},
{"id": 4, "value": 62, "friends": 6},
{"id": 5, "value": 55, "friends": 1},
{"id": 6, "value": 33, "friends": [2, 1]}
];
我怎样才能做到这一点?
我对下面的数组进行了非常基本的操作,其中我删除了数组中具有最高值的人的朋友。但当我开始执行这项更复杂的任务时,我感到很困惑。
const myArray = [
{"id": 1, "value": 75, "friends": 3},
{"id": 2, "value": 40, "friends": 4},
{"id": 3, "value": 60, "friends": 5},
{"id": 4, "value": 62, "friends": 6},
{"id": 5, "value": 55, "friends": 1},
{"id": 6, "value": 33, "friends": 2}
];
// Finds max and min values in array
var highest = Number.NEGATIVE_INFINITY;
var tmp;
for (var i=myArray.length-1; i>=0; i--) {
tmp = myArray[i].value;
if (tmp > highest) highest = tmp;
};
for(i = 0; i < myArray.length; i++){
// If person has the highest value in the array
if(myArray[i].value == highest){
// Then take away their friend
myArray[i].friends = NaN
} else {
myArray[i].friends = myArray[i].friends
}
};
console.log(myArray);