There is no problem when testing, but sometimes the error "Cannot read property of null (read 'nickname')". I posted part of the code.
let seat = [ null, null, { nickname: "user1", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe261" }, null, { nickname: "user2", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe261" }, null, null, null, null, null, null, ]; for (const i in seat) { if (seat[i].nickname === "user1") { seat[i] = null; break; } } console.log(seat);
I don’t know why sometimes there is no problem, but suddenly there is an error.
for (const i in seat) { if (seat[i] !== null && seat[i].nickname === "user1") { seat[i] = null; break; } }
I temporarily solved the problem by changing the code to the above form. I'm curious as to why...
This is because some elements in the array are null, so you should add a condition to check, like you did
seat[i] !== null
, but you can also use Optional chaining operator?.
.Reference:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Example: If your data looks like below, you don't need to add conditional or optional chaining operators.