JavaScript twoSum函数工作原理问询:`y in hash`含义及空哈希表行为疑问
Great question—let’s break this down step by step so it clicks. I’ll start with the part you’re confused about first, then walk through exactly what happens when the function runs with your example.
What does y in hash mean?
The in operator in JavaScript checks if a given property name exists in an object (including properties inherited from its prototype chain). In this code:
hashis a plain empty object at the start (const hash = {}).yis calculated astarget - x—so it’s the number we need to find in the array to add up to the target with the current elementx.
When we write y in hash, we’re asking: Does the object hash have a property whose name is the value of y?
Important note: This is different from checking hash[y] !== undefined. The in operator only cares if the property exists, not what its value is. In our twoSum case, though, we’ll always set hash[x] = i (the index of the element), so if y is in hash, it means we’ve already seen the number y earlier in the array.
How the logic works (starting with an empty hash)
Let’s walk through your example line by line to see exactly what’s happening:
Your input: arr = [2, 3, 4, 5, 6], target = 11
- Initialization:
hashstarts as an empty object{}. - First loop iteration (i = "0"):
x = nums[0] = 2y = 11 - 2 = 9- Check
9 in hash: Sincehashis empty, this returnsfalse. So we skip the return statement. - Then we add
hash[2] = "0"—nowhashis{ "2": "0" }.
- Second iteration (i = "1"):
x = 3y = 11 - 3 = 88 in hash? No—hash only has "2" as a property. Skip return.- Add
hash[3] = "1"→hashis{ "2": "0", "3": "1" }.
- Third iteration (i = "2"):
x = 4y = 11 - 4 =77 in hash? No. Skip return.- Add
hash[4] = "2"→hashbecomes{ "2": "0", "3": "1", "4": "2" }.
- Fourth iteration (i = "3"):
x =5y =11 -5=66 in hash? No. Skip return.- Add
hash[5] = "3"→hashis now{ "2": "0", "3": "1", "4": "2", "5": "3" }.
- Fifth iteration (i = "4"):
x =6y =11 -6=5- Check
5 in hash: Yes! Because we addedhash[5] = "3"in the fourth iteration. - So we return
[i, hash[y]]→["4", "3"](which maps to the indices of 6 and 5 in your array, since 6+5=11).
The key point here is that we don’t add to the hash until after we check for y. That way, we never accidentally match the current element with itself (if the array had duplicate values that add up to the target, this still works because we check first before storing the current element).
Why the empty hash isn’t a problem
At the start, hash is empty, so the first few iterations will never trigger the return—they just populate the hash with the elements we’ve already seen and their indices. By the time we hit an element that pairs with a previous one, the hash will have that previous element stored as a property, so y in hash will be true.
内容的提问来源于stack exchange,提问作者Shreyash Kolhe

