You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

关于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 write cache.n, JavaScript looks for a key literally named "n", not the value of the variable n.
  • Square bracket notation (cache[n]) lets you use a variable (like n here) as the key. It evaluates the variable first, then uses that result as the key. So if n is 5, it looks for the key 5, 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 return 85 (the value under key 5).
  • cache.n will return undefined (since we never set a key named "n" in the cache object).

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:

  1. First time you call memoizedAddTo80(n) with a new number, the code checks if that number is already a key in cache (using n in cache).
  2. If it's not there, it calculates n + 80, stores that result in cache[n], then returns it.
  3. Next time you call the function with the same n, it sees the key exists in cache, 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

火山引擎 最新活动