Reputation: 93
This is small issue but strange!
let checkedlistarr = new Array();
for (var i in items){ //items size is 30
checkedlistarr.push(i)
}
const [selected, setSelected] = React.useState(checkedlistarr);
console.log(selected)
It returns []
but
checkedlistarr = ["0","1","2","3"];
const [selected, setSelected] = React.useState(checkedlistarr);
console.log(selected)
It returns ["0","1","2","3"]
Why this happens? I tried concat function, too. but same issue.
Upvotes: 4
Views: 185
Reputation: 4470
There's a small misunderstanding may be. I believe items
must be empty or does not have iterable properties.
As from docs for-in, iterates over all enumerable properties.
Ex: If items
is a number/boolean(having not Iterable values
), for-in
loop won't even execute.
const items = 30
for(var i in items) {
console.log("this won't run") // Because `Object.getOwnPropertyDescriptors(items)` returns empty `{}`
}
If items has a Iterable properties, for..in
loop executes properly. Means
const items = new Array(30).fill(1) // fill some values or any object with values { 0: 0, 1: 1, 2: 2... }
for(var i in items) {
console.log("this will run", i) // Because `Object.getOwnPropertyDescriptors(items)` returns empty `{0, {...}, 1: {...},2...}`
}
You can see here demo with your code.
Upvotes: 1
Reputation: 167
I am sure code doesn't have a problem. The reason why it returns empty array is because of processing time.
console.log(selected);
This line would be processed before loop operation.
Upvotes: 1