英文:
How to add the key of the object to the array in js
问题
我不知道如何不重写数组'aiStaff'。请帮助我。
英文:
I have such objects:
robot {
id
skill
currentWorkPlace
}
warehouse {
aiStaff
currentStatus
boxes
}
I have to write a function that should add the id of a new worker to the aiStaff array, and write a reference to the warehouse object to the job in the currentWorkPlace. But I don't know how not to change the array in the warehouse.('registerRobot' function should not rewrite array 'aiStaff' inside 'warehouse' object) and I don't have to create a new variable
There is my code:
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff = [robot.id];
}
I dont know how to not rewrite array 'aiStaff'. Please help me Guys.
答案1
得分: 0
看起来你的 warehouse.aiStaff
是一个数组。在这种情况下,修改你的函数将机器人 ID 添加到数组中:
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push(robot.id);
}
英文:
It looks like your warehouse.aiStaff
is an array. In this case change your function to add the robot ID to the array:
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push(robot.id);
}
答案2
得分: 0
如果我理解正确,您需要“添加”一个新的机器人,但您遇到了整个数组被覆盖的问题。
考虑到warehouse.aiStaff
是一个数组,如果您想要添加一个新的“worker”,您需要将新项目使用push
方法添加到数组中。
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push({
id: robot.id
});
}
英文:
If I understood correctly you need to 'add' a new robot, but you are having the issue that the entire array gets overridden.
Considering warehouse.aiStaff
is an array, if you want to add a new 'worker' you need to push
the new item into the array.
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push({
id: robot.id
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论