js cheat sheet

-


strict 模式

未使用 var 申明变量就使用的,将导致运行错误。

启用 strict 模式的方法是在 JavaScript 代码的第一行写上:"use strict";


数据类型

Number

JavaScript 不区分整数和浮点数,统一用 Number 表示,以下都是合法的 Number 类型:

1
2
3
4
5
6
123; // 整数123
0.456; // 浮点数0.456
1.2345e3; // 科学计数法表示1.2345x1000,等同于1234.5
-99; // 负数
NaN; // NaN表示Not a Number,当无法计算结果时用NaN表示
Infinity; // Infinity表示无限大,当数值超过了JavaScript的Number所能表示的最大值时,就表示为Infinity

字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 定义
let a = "hello";
let b = "hello";
let c = `hello
world`;

// 模板字符串
let d = `${a},${b}`;

// split and join
a = a.split("");
a = a.join("-");

// index
let a = "hello world";
let b = "world";

console.log(a.indexOf(b)); //6
console.log(a.indexOf("aa")); //-1

布尔值

  • true
  • false

null

null 表示一个空的值。

undefined

undefined 表示值未定义。

数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// let nums = new Array(1, 2, 3, 4, 5);
let nums = [1, 2, 3, 4, 5];
console.log(nums);

// index
let num = nums[0];

// reverse
nums.reverse();
console.log(nums); //[ 5, 4, 3, 2, 1 ]

// push
// append data to the end of an array
nums.push(6);
console.log(nums); //[ 5, 4, 3, 2, 1, 6 ]

// pop
num = nums.pop();
console.log(nums); //[ 5, 4, 3, 2, 1 ]
console.log(num); //6

// shift
// removes the first element of an array
num = nums.shift();
console.log(nums); // [ 4, 3, 2, 1 ]
console.log(num); // 5

// unshift
nums.unshift(num);
console.log(nums); //[ 5, 4, 3, 2, 1 ]

// splice
// first parameter is the index, the second indicates the number of elements to delete.
let nums1 = nums.splice(2, 2);
console.log(nums); //[ 5, 4, 1 ]
console.log(nums1); //[ 3, 2 ]
// the third parameter, represents one or more elements, let us add them
nums.splice(2, 0, nums1);
console.log(nums); //[ 5, 4, [ 3, 2 ], 1 ]

// slice
// Copies a given number of elements to a new array and leaves the original array untouched
nums = [1, 2, 3, 4, 5];
nums1 = nums.slice(1, 3);
console.log(nums); // [ 1, 2, 3, 4, 5 ]
console.log(nums1); // [ 2, 3 ]

// index
let index1 = nums.indexOf(5);
let index2 = nums.indexOf(0);
console.log(index1);
console.log(index2);

// includes
let b = nums.includes(3);
console.log(b);

// ES6 The Spread Operator
console.log(nums);
let max = Math.max(...nums);
console.log(max);
// [...new Set(arr)] = unique value array
let arr = [1, 2, 2, 3, 3, 4, 5, 5];
let uniq = [...new Set(arr)];
console.log(uniq); // [1,2,3,4,5]

// Destructuring Arrays to Assign Variables
[a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); // 1, 2
// it can access any value by using commas to reach the desired index
[a, b, , , c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); // 1, 2, 5
// to collect the rest of the elements into a separate array.
[a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a, b); // 1, 2
console.log(arr); // [3, 4, 5, 7]

对象

对象是一组由键-值组成的无序集合。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
let cat = {
name: "Whiskers",
legs: 4,
tails: 1,
enemies: ["Water", "Dogs"]
};

// Object.fromEntries: Object from Map
// node>12
let obj1 = Object.fromEntries([
["a", 1],
["b", 2],
["c", 3]
]);
console.log(obj1);

obj = Object.fromEntries(map);

// Accessing Objects Properties
// Accessing with dot (.) notation
let name = cat.name;
console.log(name); // Whiskers
// Accessing with bracket ([]) notation
let legs = cat["legs"];
console.log(legs);
// Accessing with variables
let tails = "tails";
console.log(cat[tails]);

// Creating an array from the keys of an object
let arr = [];
for (let key in cat) {
arr.push(key);
}
console.log(arr);

// Test Object Properties
let b1 = cat.hasOwnProperty("legs");
let b2 = cat.hasOwnProperty("legs1");
console.log(b1); //true
console.log(b2); //false

// Destructuring Variables from Objects
var voxel = { x: 3.6, y: 7.4, z: 6.54 };
const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54

Map

  • new Map() – creates the map.
  • map.set(key, value) – stores the value by the key.
  • map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
  • map.has(key) – returns true if the key exists, false otherwise.
  • map.delete(key) – removes the value by the key.
  • map.clear() – removes everything from the map.
  • map.size – returns the current element count.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
let map = new Map();

// set
map.set("a", 1);
map.set("b", 2);
console.log(map);

// get
let a = map.get("a");
console.log(a);

// has
let bool = map.has("a");
console.log(bool);

// delete
map.delete("a");
console.log(map);

// clear
map.clear();

// size
let size = map.size;
console.log(size);

// use objects as keys.
let john = { name: "John" };
map.set(john, 1);
console.log(map);

// chaining
map.set("1", "str1")
.set(1, "num1")
.set(true, "bool1");
console.log(map);

Iteration over Map

  • map.keys() – returns an iterable for keys,
  • map.values() – returns an iterable for values,
  • map.entries() – returns an iterable for entries [key, value], it’s used by default in for..of.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
let map = new Map();
map.set("a", 1)
.set("b", 2)
.set("c", 3);

// When a Map is created, we can pass an array (or another iterable) with key/value pairs for initialization, like this:
map = new Map([
["a", 1],
["b", 2],
["c", 3]
]);
// Object.entries: Map from Object
let obj = {
a: 1,
b: 2,
c: 3
};
map = new Map(Object.entries(obj));
console.log(map);

// key
for (let key of map.keys()) {
// console.log(key);
}

let arr = [...map.keys()];
// console.log(arr);

// value
for (let value of map.values()) {
// console.log(value);
}

// entry
for (const entry of map) {
// console.log(entry);
}

// The iteration goes in the same order as the values were inserted. Map preserves this order, unlike a regular Object.
// forEach
map.forEach((value, key) => {
// console.log(value, key);
});

Set

  • new Set(iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
  • set.add(value) – adds a value, returns the set itself.
  • set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
  • set.has(value) – returns true if the value exists in the set, otherwise false.
  • set.clear() – removes everything from the set.
  • set.size – is the elements count.
1
2
3
4
5
6
7
8
9
10
let set = new Set([1, 2, 3, 4, 5, 3, 5]);
console.log(set);

for (const num of set) {
console.log(num);
}

set.forEach(element => {
console.log(element);
});

声名变量

  • var
  • let
  • const

let 的用法类似于 var,但是 let 只在所在的代码块内有效,所以一般使用 let 替代 var。而 const 用来声明常量。


运算符

operator Meaning
== Equality
=== Strict Equality
!= Inequality
!== Strict Inequality
> Greater Than
>= Greater or Equal Than
< Less Than
<= Less or Equal Than
&& And
| Or
% 取余数

NaN 这个特殊的 Number 与所有其他值都不相等,包括它自己,唯一能判断 NaN 的方法是通过 isNaN()函数。

==比较,它会自动转换数据类型再比较,很多时候,会得到非常诡异的结果
===比较,它不会自动转换数据类型,如果数据类型不一致,返回 false,如果一致,再比较。
由于 JavaScript 这个设计缺陷,不要使用==比较,始终坚持使用===比较

1
2
console.log(NaN === NaN); //false
console.log(isNaN(NaN)); //true

循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// while
let i = 0;
while (i < 10) {
console.log(i);
i += 1;
}

// for
for (let i = 0; i < 10; ++i) {
console.log(i);
}

// for in 遍历对象
let object = {
a: 1,
b: 2
};
for (const key in object) {
if (object.hasOwnProperty(key)) {
const element = object[key];
console.log(element);
}
}

// ES6 for-of 遍历数组
let nums = [1, 2, 3, 4, 5];
for (const num of nums) {
console.log(num);
}

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5);
console.log(answer); // 8

// Immediately Invoked Function Expression or IIFE
(function() {
console.log("A cozy nest is ready");
})();

// ES6 Arrow Functions
const myFunc1 = () => {
const myVar = "value";
return myVar;
};
// and if there is no function body, and only a return value
const myFunc2 = () => "value";

// ES6 Higher Order Arrow Functions
let nums = [1, 2, 3, 4, 5, 6, 7];
nums = nums.filter(num => num % 2 === 0);
console.log(nums);

// ES6 Declarative Functions within Objects
// When defining functions within objects in ES5, we have to use the keyword function
const person = {
name: "Taylor",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
// With ES6, You can remove the function keyword and colon
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};

function howMany(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments
console.log(howMany("string", null, [1, 2, 3], {})); // You have passed 4 arguments.

正则表达式

Character Description
\ Escapes a special character.
| Search for multiple patterns. To match “yes” or “no”, the regex is /yes
i This flag is used to ignore upper and lowercase. /ignorecase/i.
g Search or extract a pattern more than once.
. The wildcard character . will match any character except new lines.
[] Allow you to define the characters to match. /b[au]g/ will match “bag”, “bug” but not “bog”.
[a-z] Match all the characters between a and z.
[1-9] Match all the numbers between 1 and 9.
[a-z1-9] Match all the character between a and z, and the numbers between 1 and 9.
[^] Match the characters not in the set. [^a-e] match all other characters except A, B, C, D, and E.
+ Match 1 or more occurrences of the previous character in a row.
* Match 0 or more occurrences of the previous character.
? Match 0 or 1 occurrence of the previous character. Useful for Lazy matching.
^ Search for patterns at the beginning of strings.
$ Search for patterns at the end of a string.
\w Equal to [A-Za-z0-9_]. Matches upper, lowercase, numbers the and underscore character (-).
\W Matches any nonword character. Equivalent to [^a-za-z0-9_].
\d Equal to [0-9]. Match one digit.
\D Equal to [^0-9]. Match one non digit.
\s Match a whitespace.
\S Match everything except whitespace.
a{2,5} Match the letter a between 3 and 5 times.
a{2,} Specify only the lower number of matches.
a{5} Specify the exact number of matches.
(…) Specify a group that can be acceded with number (from 1)
  • Regex Methods
Method Description
test() Returns true or false if the pattern match a string or not.
match() Extract the actual matches found.
replace() Search and replace text in a string .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// test method returns true or false if the pattern match a string or not
let myString = "hello world";
let myRegex = /hello/;
let result = myRegex.test(myString);
// console.log(result);

// extract the matches of a regex with the match method
let extractStr = "Extract the world 'coding' from this string";
let codingRegex = /coding/;
result = extractStr.match(codingRegex);
// console.log(result);

// Search and replace
let wrongText = "The sky is silver.";
let silverRegex = /silver/;
wrongText = wrongText.replace(silverRegex, "blue"); // Returns "The sky is blue."
// console.log(wrongText);

// search for multiple patterns using the alternation or OR operator: |
let petString = "James has a pet cat.";
let petRegex = /dog|cat|bird|fish/;
result = petRegex.test(petString);
// console.log(result);

// ignore upper or lowercase
let myString1 = "freeCodeCamp";
let fccRegex = /freeCodecamp/i; // flag i
result = fccRegex.test(myString1);
// console.log(result);

// Search or extract a pattern more than once
let twinkleStar = "Twinkle, twinkle, little star";
let starRegex = /Twinkle/gi; // a regex can have multiple flags
result = twinkleStar.match(starRegex);
// console.log(result);

// The wildcard character . will match any character except new lines.
let exampleStr = "Let's have fun with regular expressions!";
let unRegex = /.un/;
result = unRegex.test(exampleStr);
result = unRegex.exec(exampleStr);
result = exampleStr.match(unRegex);
// console.log(result);

// define the characters to match, in this example all the vowels in quoteSample
let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it.";
let vowelRegex = /[aeiou]/gi;
result = quoteSample.match(vowelRegex);
// console.log(result);

// Match all the characters in quoteSample (between a and z)
let quoteSample1 = "The quick brown fox jumps over the lazy dog.";
let alphabetRegex = /[a-z]/gi;
result = quoteSample1.match(alphabetRegex);
console.log(result);

// Match all the character between two characters and numbers
let quoteSample2 = "Blueberry 3.141592653s are delicious.";
let myRegex2 = /[h-s2-6]/gi;
result = quoteSample2.match(myRegex2);
console.log(result);

// Match all that is not a number or a vowel
let quoteSample3 = "3 blind mice.";
let myRegex3 = /[^aeiou0-9]/gi;
result = quoteSample3.match(myRegex3);
console.log(result);

// Match 1 or more occurrences of the previous character (* for 0 or more)
let difficultSpelling = "Mississippi";
let myRegex4 = /s+/g;
result = difficultSpelling.match(myRegex4);
console.log(result);

// ? Match 0 or 1 occurrence of the previous character. Useful for Lazy matching
let text = "titanic";
// let myRegex5 = /t[a-z]*?i/;
let myRegex5 = /t[a-z]*?i/g;
result = text.match(myRegex5);
console.log(result);

// Search for patterns at the beginning of strings
let rickyAndCal = "Cal and Ricky both like racing.";
let calRegex = /^Cal/;
result = calRegex.test(rickyAndCal);
console.log(result);

// Search for patterns at the end of a string
let caboose = "The last car on a train is the caboose";
let lastRegex = /caboose$/;
result = lastRegex.test(caboose);
console.log(result);

// \w is equal to [A-Za-z0-9_]
let quoteSample = "The five boxing wizards jump quickly.";
let alphabetRegexV2 = /\w/g;
let result = quoteSample.match(alphabetRegexV2).length;

// Match only 3 to 6 letter h's in the word "Oh no"
let ohStr = "Ohhh no";
let ohRegex = /Oh{3,6} no/;
let result = ohRegex.test(ohStr);

// Match both the American English (favorite) and the British English (favourite) version of the word
let favWord = "favorite";
let favRegex = /favou?rite/;
let result = favRegex.test(favWord);

// Groups () let you reuse patterns
let repeatNum = "42 42 42";
let reRegex = /^(\d+)\s\1\s\1$/; // every 1 represent the group (\d+)
let result = reRegex.test(repeatNum);

// Remove all the spaces at the beginning an end of a string
let hello = " Hello, World! ";
let wsRegex = /^\s+(.*\S)\s+$/;
let result = hello.replace(wsRegex, "$1"); // returns 'Hello, World!'

面向对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
let duck = {
name: "aflac",
numLegs: 2,
sayName() {
console.log(this.name);
}
};

duck.sayName();

// constructor
function Bird(name, color) {
this.name = name;
this.color = color;
this.sayName = function() {
return this.name;
};
}

// create a new instance of Bird
let cardinal = new Bird("Bruce", "red");
let duck = new Bird("Donald", "blue");

// access and modify blueBird object
cardinal.name; // Bruce
cardinal.color; // red
cardinal.color = green;
cardinal.color; // green

// check if an object is an instance of a constructor
cardinal instanceof Bird; // true
crow instanceof Bird; // false

// check an objects own (name, color, numLegs) properties
cardinal.hasOwnProperty("color"); // true
cardinal.hasOwnProperty("age"); // false

//check an objects properties with the constructor property
cardinal.constructor === Bird; // true

// use constructor.prototype to add new properties to object constructors
Bird.prototype.cute = true;
cardinal.cute; // true
crow.cute; // true

// add more than one property and method to a constructor
Bird.prototype = {
constructor: Bird, // specify the constructor
numLegs: 2, // new property

eat: function() {
// new method
console.log("nom nom nom");
},

describe: function() {
// new method
console.log("My name is " + this.name);
}
};

let chicken = new Bird("Dinner", "brown");
chicken.numLegs; // 2
chicken.eat(); // nom nom nom
chicken.describe(); // My name is Dinner
  • 继承
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function Animal() {}
Animal.prototype.eat = function() {
console.log("nom nom nom");
};

// Dog constructor
function Dog() {}

// make the Gog constructor inherit the eat function from Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.bark = function() {
console.log("wof wof!");
};

// the new object will have both, the inherited eat() and its own bark() method
let beagle = new Dog();
beagle.eat(); // "nom nom nom"
beagle.bark(); // "Woof!"

// override an inherited method
Dog.prototype.eat = function() {
return "nice meeeeat!";
};

let doberman = new Dog();
doberman.eat(); // nice meeeeat!
  • Mixins
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let bird = {
name: "Donald",
numLegs: 2
};

let boat = {
name: "Warrior",
type: "race-boat"
};

// this mixin contain the glide method
const glideMixin = function(obj) {
obj.glide = function() {
console.log("gliding...");
};
};

// the object is passed to the mixin and the glide method is assigned
glideMixin(bird);
glideMixin(boat);

bird.glide(); // "gliding..."
boat.glide(); // "gliding..."
  • Closures to Protect Properties
1
2
3
4
5
6
7
8
9
10
11
12
13
function Bird() {
// instead of this.hatchedEgg...
let hatchedEgg = 10; // private property

this.getHatchedEggCount = function() {
// publicly available method that a bird object can use
return hatchedEgg;
};
}

let ducky = new Bird();
ducky.hatchedEgg = 2; // nothing happens
ducky.getHatchedEggCount; // 10
  • Modules
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let funModule = (function() {
return {
isCuteMixin: function(obj) {
obj.isCute = function() {
return true;
};
},

singMixin: function(obj) {
obj.sing = function() {
console.log("Singing to an awesome tune");
};
}
};
})();

function Dog() {}
let goodBoy = new Dog();

// assign the singMixin method to the goodBoy object
funModule.singMixin(goodBoy);
goodBoy.sing(); // Singing to an awesome tune

ES6 面向对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}

getSummary() {
return `${this.title} was written by ${this.author} in ${this.year}`;
}

getAge() {
const years = new Date().getFullYear() - this.year;
return `${this.title} is ${years} years old`;
}
}

book = new Book("Book One", "John Doe", 2016);
book.getSummary(); // Book One was written by John Doe in 2016
book.getAge(); // Book One is 3 years old
  • getters and setters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Book {
constructor(author) {
this._author = author;
}
// getter
get writer() {
return this._author;
}
// setter
set writer(updatedAuthor) {
this._author = updatedAuthor;
}
}
const lol = new Book("anonymous");
console.log(lol.writer); // anonymous
lol.writer = "wut";
console.log(lol.writer); // wut
  • Statics Methods
1
2
3
4
5
6
7
8
9
10
11
12
13
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}

static sayHi() {
return "Hi!";
}
}

Book.sayHi(); // Hi!
  • Inheritance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}

getSummary() {
return `${this.title} was written by ${this.author} in ${this.year}`;
}
}

class Magazine extends Book {
constructor(title, author, year, month) {
super(title, author, year);
this.month = month;
}

sayHi() {
return "Hi!";
}
}

mag = new Magazine("Mag", "People", 2019, "jan");
mag.getSummary(); // Mag was written by People in 2019
mag.sayHi(); // Hi!

函数式编程

  • map
  • filter
  • reduce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let nums = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(nums);

// map
nums = nums.map(num => num + 1);
console.log(nums);

// filter
nums = nums.filter(num => num % 2 == 0);
console.log(nums);

// reduce
let sum = nums.reduce((a, b) => a + b);
console.log(sum);

ES6 import and export

  • import
1
2
3
4
5
6
// we can choose which parts of a module or file to load into a given file.
import { function } from "file_path";
// We can also import variables the same way!

// Import Everything from a File
import * as name_of_your_choice from "file_path";
  • export
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const capitalizeString = string => {
return string.charAt(0).toUpperCase() + string.slice(1);
};
export { capitalizeString }; //How to export functions.
export const foo = "bar"; //How to export variables.

// Alternatively, if you would like to compact all your export statements into one line, you can take this approach
const capitalizeString = string => {
return string.charAt(0).toUpperCase() + string.slice(1);
};
const foo = "bar";
export { capitalizeString, foo };

// use export default if only one value is being exported from a file.
// It is also used to create a fallback value for a file or module
export default function add(x, y) {
return x + y;
}
// and to import
import add from "math_functions";
add(5, 4); //Will return 9

查看类型

  • type

客户端存储

  • cookie
  • Local Storage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let map = new Map();
map.set(360, [{ a: 1 }, { b: 2 }]);
map.set(94, [{ c: 1 }, { d: 2 }]);

let mapString = JSON.stringify(Array.from(map));
localStorage.setItem("map", mapString);
map = new Map(JSON.parse(localStorage.getItem("map")));

for (const key of map.keys()) {
console.log(key);
console.log(typeof key);
console.log(map.get(key));
}

map.get(360).push({ e: 5 });
console.log(map);
mapString = JSON.stringify(Array.from(map));

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×