- JavaScript:Moving to ES2015
- Ved Antani Simon Timms Narayan Prusty
- 375字
- 2021-07-09 19:07:35
Sets
ECMAScript 6 introduces sets. Sets are collections of values and can be iterated in the order of the insertion of their elements. An important characteristic about sets is that a value can occur only once in a set.
The following snippet shows some basic operations on sets:
var mySet = new Set(); mySet.add(1); mySet.add("Howdy"); mySet.add("foo"); mySet.has(1); // true mySet.delete("foo"); mySet.size; // 2 for (let item of mySet) console.log(item); // 1 // "Howdy"
We discussed briefly that JavaScript arrays are not really arrays in a traditional sense. In JavaScript, arrays are objects that have the following characteristics:
- The
length
property - The functions that inherit from
Array.prototype
(we will discuss this in the next chapter) - Special handling for keys that are numeric keys
When we write an array index as numbers, they get converted to strings—arr[0]
internally becomes arr["0"]
. Due to this, there are a few things that we need to be aware of when we use JavaScript arrays:
- Accessing array elements by an index is not a constant time operation as it is in, say, C. As arrays are actually key-value maps, the access will depend on the layout of the map and other factors (collisions and others).
- JavaScript arrays are sparse (most of the elements have the default value), which means that the array can have gaps in it. To understand this, look at the following snippet:
var testArr=new Array(3); console.log(testArr);
You will see the output as
[undefined, undefined, undefined]
—undefined
is the default value stored on the array element.
Consider the following example:
var testArr=[]; testArr[3] = 10; testArr[10] = 3; console.log(testArr); // [undefined, undefined, undefined, 10, undefined, undefined, undefined, undefined, undefined, undefined, 3]
You can see that there are gaps in this array. Only two elements have elements and the rest are gaps with the default value. Knowing this helps you in a couple of things. Using the for...in
loop to iterate an array can result in unexpected results. Consider the following example:
var a = []; a[5] = 5; for (var i=0; i<a.length; i++) { console.log(a[i]); } // Iterates over numeric indexes from 0 to 5 // [undefined,undefined,undefined,undefined,undefined,5] for (var x in a) { console.log(x); } // Shows only the explicitly set index of "5", and ignores 0-4
- Java加密與解密的藝術(shù)(第2版)
- 編寫高質(zhì)量代碼:改善Python程序的91個(gè)建議
- 零基礎(chǔ)學(xué)Java(第4版)
- Amazon S3 Cookbook
- Hands-On Reinforcement Learning with Python
- Spring+Spring MVC+MyBatis整合開發(fā)實(shí)戰(zhàn)
- MongoDB,Express,Angular,and Node.js Fundamentals
- 基于SpringBoot實(shí)現(xiàn):Java分布式中間件開發(fā)入門與實(shí)戰(zhàn)
- Scala編程(第5版)
- HTML+CSS+JavaScript網(wǎng)頁(yè)制作:從入門到精通(第4版)
- 交互式程序設(shè)計(jì)(第2版)
- 玩轉(zhuǎn).NET Micro Framework移植:基于STM32F10x處理器
- Building Slack Bots
- HTML5移動(dòng)Web開發(fā)
- Java網(wǎng)絡(luò)編程實(shí)用精解