gpt4 book ai didi

javascript - 保存 JSON 对象键时数组长度和数组元素不正确

转载 作者:行者123 更新时间:2023-11-28 14:34:37 25 4
gpt4 key购买 nike

我有一个带有 JSON 对象响应数组的 API,如下所示

[
{
person_id:"12212",
person_name:"some name",
deptt : "dept-1"
},
{
person_id: "12211",
person_name: "some name 2"
deptt : "dept-2"
},

]

我试图将 person_id 的值保存在数组中,但这些值未正确保存,因此数组长度不正确。

由于我正在使用 Chakram,这就是我目前正在做的事情

it('gets person id in array',()=>{
let array_ids =[];
let count=0;
return response.then((api_response)=>{
for(var i=1;i<api_response.body.length;i++){
//this is correctly printing the person id of response
console.log('Person ids are ==>'+api_response.body[i].person_id);
count++;

//this is not working
array_ids = api_response.body[i].person_id;
}
console.log('Count is '+count) //prints correct number
console.log('Array length '+array_ids.length) //prints incorrect length - sometimes 11, sometimes 12
});
});

我想知道为什么会出现这种情况?是

array_ids = api_response.body[i].person_id 

获取/分配数组中元素的错误方法?

最佳答案

试试这个,您的代码中有一个更正。您不是将 ID 插入数组,而是每次都分配新的 ID 值。

it('gets person id in array',()=>{
let array_ids =[];
let count=0;
return response.then((api_response)=>{
for(var i=1;i<api_response.body.length;i++){
//this is correctly printing the person id of response
console.log('Person ids are ==>'+api_response.body[i].person_id);
count++;

//this is not working
array_ids.push(api_response.body[i].person_id); //update
}
console.log('Count is '+count) //prints correct number
console.log('Array length '+array_ids.length) //prints incorrect length - sometimes 11, sometimes 12
});
});

关于javascript - 保存 JSON 对象键时数组长度和数组元素不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com