In this code I'm checking if every key in the obj is squared value of arr. also checking if values of obj is equal to corresponding value quantity of arr. so I'm iterating arr and by using in operator checking if key ** 2 exists in obj, if not doing console.log("false") if yes making subtraction of obj's property and doing console.log("true")
let obj = {
1: 1,
4: 1,
9: 1,
25: 2,
};
let arr = [1, 2, 3, 2, 5];
for (let key of arr) {
if (!(key ** 2 in obj)) {
console.log("false");
} else {
obj[key ** 2] -= 1;
console.log(obj);
console.log("true");
}
}
Here I changed in operator with (obj[key ** 2]), so my question is not how to solve task properly, my question is that why in case of in operator and "(obj[key ** 2])" they act the way they do? in the in operator case subtraction of -1 continues, but in the second case, the moment when obj's key is 4 and property 0 it stops subtraction, which means that !(obj[2 ** 2]) is true therefore logs "false".
so again why in the both case they act the way they do? is there some rule or something like that? I think first case seems more logically, Thanks in advance
let obj = {
1: 1,
4: 1,
9: 1,
25: 2,
};
let arr = [1, 2, 3, 2, 5];
for (let key of arr) {
if (!(obj[key ** 2])) {
console.log("false");
} else {
obj[key ** 2] -= 1;
console.log(obj);
console.log("true");
}
}
2 ** 2 = 4and whenobj[4] = 0, thenif (!0)will go in the first branch and print"false".