关于JavaScript中cache[n]用法及与cache.n区别的技术问询
Hey there! Let's break this down nice and simple since you're new to JavaScript—no fancy jargon, just straight talk.
First: What is cache[n]?
cache is an empty object we declared with let cache = {};. In JavaScript, objects store data as key-value pairs (think of keys as labels, values as the data tied to those labels).
cache[n] is how we access or set the value tied to the key that matches the value of n (the parameter passed to the function). For example, if you call memoizedAddTo80(5), n is 5, so cache[5] refers to the value stored under the key 5 in the cache object.
Why use [n] instead of dot notation (cache.n)?
Great question! The difference comes down to how JavaScript interprets keys:
- Dot notation (
cache.n) only works when the key is a fixed, valid identifier (like a standard variable name—can't start with a number, have spaces, or be a variable itself). When you writecache.n, JavaScript looks for a key literally named"n", not the value of the variablen. - Square bracket notation (
cache[n]) lets you use a variable (likenhere) as the key. It evaluates the variable first, then uses that result as the key. So ifnis 5, it looks for the key5, not"n".
Are cache[n] and cache.n equal?
Nope, they're totally different! Let's use an example:
If you run memoizedAddTo80(5), the code will set cache[5] = 85.
cache[5]will return85(the value under key5).cache.nwill returnundefined(since we never set a key named"n"in thecacheobject).
The only time they'd be the same is if n was the string "n" (like memoizedAddTo80("n")), but that's a rare edge case here.
Why does this code use cache[n]?
This is a classic example of memoization—a technique to speed up functions by storing results of repeated (or expensive) calculations. Here's how it works:
- First time you call
memoizedAddTo80(n)with a new number, the code checks if that number is already a key incache(usingn in cache). - If it's not there, it calculates
n + 80, stores that result incache[n], then returns it. - Next time you call the function with the same
n, it sees the key exists incache, so it just returns the stored value instead of recalculating it.
Even though adding 80 is super simple, this pattern is incredibly useful for functions that do heavy work (like API calls, complex math, or data processing)—it saves you from repeating work that's already been done!
内容的提问来源于stack exchange,提问作者Dickens




