最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What does a variable directly followed by empty curly braces mean in Javascript? - Stack Overflow

programmeradmin7浏览0评论

Going through the Eloquent Javascript book where I encountered something I haven't seen before.

In the code snippet below the variable 'map' is followed by empty curly braces. Can someone please explain what this means? Does this do anything tot he function that follows.

Also, can someone explain what map[event] = phi; does exactly? I take it this map refers to the variable 'map' we declared in the first line...

var map = {};
function storePhi (event, phi) {
  map[event] = phi;
}

storePhi("pizza", 0.069);

Going through the Eloquent Javascript book where I encountered something I haven't seen before.

In the code snippet below the variable 'map' is followed by empty curly braces. Can someone please explain what this means? Does this do anything tot he function that follows.

Also, can someone explain what map[event] = phi; does exactly? I take it this map refers to the variable 'map' we declared in the first line...

var map = {};
function storePhi (event, phi) {
  map[event] = phi;
}

storePhi("pizza", 0.069);
Share Improve this question asked Jun 24, 2016 at 16:23 Ronny BlomRonny Blom 1492 silver badges6 bronze badges 4
  • map = {} is declaring an object. map[event] = phi is adding a property to map where the name is equal to the value of event and phi is the associated value. – Mike Cluck Commented Jun 24, 2016 at 16:24
  • 3 Possible duplicate of JavaScript arrays braces vs brackets – Adam Buchanan Smith Commented Jun 24, 2016 at 16:24
  • 2 What have you tried? Have you done even basic research? A quick google search for "curly braces in Javascript" answers your question... – Luke Taylor Commented Jun 24, 2016 at 16:25
  • I did indeed do research Luke Taylor. I hadn't yet seen an empty object being declared. I was probably overthinking the significance of it. I now see that this specific example shows that the object is 'filled' in the next steps. – Ronny Blom Commented Jun 24, 2016 at 16:39
Add a comment  | 

2 Answers 2

Reset to default 14

The {} represents an empty object.

map[event] = phi will add (or overwrite) a property on the map object with the name event and assign it to a value of phi. This way, you can do map.EVENT_NAME to get the value of phi for that event.

After performing storePhi("pizza", 0.069);, map will look like this:

console.log(map);
map = {
  pizza: 0.069
}

console.log(map.pizza);
map.pizza = 0.069

It means the variable is a dictionary that stores key value pairs. The subscript or the value within the [] brackets is the key and the value on the right side is the value.

发布评论

评论列表(0)

  1. 暂无评论