课程: JavaScript: Maps and Sets

Get your set size

- [Instructor] One of the wonderful things about learning about maps and sets in tandem is that there are so many overlapping concepts, including the size property. Sets have a single property as well, size, to let us know how many elements are contained within the set. The syntax is really simple. You apply the property directly on your set and it will return a number indicating how many values are in your set. Remember, this is a property, not a method, so we don't need parentheses to execute it as we do with methods. Let's revisit our birthday invites example. We create a new variable, inviteSize, and set that equal to invites.size. If we log that out, we'd see that it returns 4. Remember, sets do not contain duplicate values. All right, now let's head to the code and try an example together. In keeping with our ice cream set example, we want to find out how many items are in our set. For this example, let's just simply log the answer out, instead of setting it to a variable. I'll set up my console log and then we will use template literals, and I'll say "Our set is" and then I'll use my dollar sign and curly braces. And within this I'll use our iceCream set and apply the size property. So I'm going to say, "Our set is" and then whatever the number elements, or we'll say, "Our set contains" X elements. All right, and then if I run this down here, I'll see that our set contains four elements. All right, and remember, if we didn't have the knowledge that we have about sets and the duplicate values, we may look at our set up above, where we've added each of the values, and think, "Why does that only return four elements?" But remember no duplicate values in a set.

内容