因此,我最近了解到可以将对象用作数组中的数据类型。 因此,我需要做的是遍历此数组,并添加每个年龄,然后将年龄总和除以数组的长度,以得出所有人的平均年龄。事情是我不明白您怎么称呼给定的钥匙。
我知道要调用第一个对象,您将编写“ people [0]”,但我不知道如何从该对象获取键并将其传递给函数。
let people=[ {name:'Don', Age:23},
{name:'Ron', Age:21},
{name:'Juan', Age:20}
]
// return /people.length
答案 0 :(得分:3)
希望这会有所帮助。
char receive[1024];
int read = recv(client_socket, &receive, 1024, 0);
receive[read] = '\0';
char *token = strtok(receive, " "); // get the first part
while (token != NULL) { // while there still have unprocessed parts
// handle the commands, values, whatever you want
if (strcmp(receive, "user") == 0) {
printf("User has requested chat with....");
}
token = strtok(NULL, " "); // get the next part
}
答案 1 :(得分:1)
如果要添加年龄,然后除以数组长度以获得平均值,在这种情况下,您可以简单地使用Array.map()
let people=[
{name:'Don', Age:23},
{name:'Ron', Age:21},
{name:'Juan', Age:20}]
//Sum
let sum = 0;
//Map
people.map((value)=> {
sum += value.Age;
})
//Average Result
let avg_Age = sum / people.length
console.log('Average Age', avg_Age)
答案 2 :(得分:1)
您可以使用以下代码遍历对象和访问键: 让总和= 0;
for(let i=1;i<=people.length;i++) {
sum = sum + people[i-1].Age;
}
console.log(sum/people.length);
//output
21.333333333333332
您还可以使用foreach方法遍历数组。 https://www.w3schools.com/jsref/jsref_obj_array.asp 通过此链接,您可以找到用于数组/对象操作的所有方法。
答案 3 :(得分:0)
要获取密钥,请致电Object.keys(people[0])
请看看Object.keys
方法
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys