Skip to content

Commit

Permalink
Merge pull request #322 from cyh0968/issue23
Browse files Browse the repository at this point in the history
Complete issue23: add more exercise on map
  • Loading branch information
Swap76 committed Oct 31, 2019
2 parents 8cee191 + 2a9f940 commit 4ddc159
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 1 deletion.
46 changes: 45 additions & 1 deletion JavaScript_Advance/map_object.js
Expand Up @@ -59,4 +59,48 @@ for (const amount of recipeMap.values()) {
// iterate over [key, value] entries
for (const entry of recipeMap) { // the same as of recipeMap.entries()
alert(entry); // cucumber,500 (and so on)
}
}

/*
Loop with forEach
Instead of using for loop, forEach can be used.
map.forEach(function(value, key){
});
or with array function
map.forEach((value, key) => {
})
*/

recipeMap.forEach((value, key) => {
alter(key + " = " + value);
});

/*
Convert To Arrays
A map obejct can be convert to arrays
var array = Array.from(map) - create an array of the key-value pairs
var array = Array.from(map.value()) - Create an array of the values
var array = Array.from(map.key()) - Create an array of the keys
*/

// create an array of the key-value pairs
const keyValArr = Array.from(recipeMap);
alter(keyValArr);

// Create an array of the values
const ValArr = Array.from(recipeMap);
alter(ValArr);

// Create an array of the keys
const keyArr = Array.from(recipeMap);
alter(keyArr);
51 changes: 51 additions & 0 deletions docs/JavaScript_Advance/map_object.md
Expand Up @@ -64,3 +64,54 @@ iterate over [key, value] entries
alert(entry); // cucumber,500 (and so on)
}
```

Loop with forEach
Instead of using for loop, forEach can be used.

```js
map.forEach(function(value, key){

});
```
or with array function
```js
map.forEach((value, key) => {

})
```

```js
recipeMap.forEach((value, key) => {
alter(key + " = " + value);
});
```
Convert To Arrays
A map obejct can be convert to arrays

```js
var array = Array.from(map) // create an array of the key-value pairs

var array = Array.from(map.value()) // Create an array of the values

var array = Array.from(map.key()) // Create an array of the keys

```

Create an array of the key-value pairs
```js
const keyValArr = Array.from(recipeMap);
alter(keyValArr);
```

Create an array of the values
```js
const ValArr = Array.from(recipeMap);
alter(ValArr);
```

Create an array of the keys
```js
const keyArr = Array.from(recipeMap);
alter(keyArr);
```

0 comments on commit 4ddc159

Please sign in to comment.