From 1d0d39b2d39070a9ece7377fbd8a304a968839fb Mon Sep 17 00:00:00 2001 From: Dmitriy Gusev Date: Tue, 19 Mar 2019 11:53:33 +0200 Subject: [PATCH 1/2] Indexes of array items and array length --- .../2019-03-19-indexes-and-length-of-array.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/shared/md/2019-03-19-indexes-and-length-of-array.md diff --git a/src/shared/md/2019-03-19-indexes-and-length-of-array.md b/src/shared/md/2019-03-19-indexes-and-length-of-array.md new file mode 100644 index 00000000..a43f2cb0 --- /dev/null +++ b/src/shared/md/2019-03-19-indexes-and-length-of-array.md @@ -0,0 +1,38 @@ +**Never add items to array usin indexes. Never trust them!** + +Lets create an empty array, and check its length is `0` +``` + var arr = []; + arr.length; // 0 +``` + +Lets add something to its first place: + +``` + arr[0] = 'I am the first'; + arr.length; // 1 +``` + +Oh, what if... + +``` + arr[15] = 'actually, i am the second'; + arr.length; // 16 +``` + +***WTF?*** + +Array actually looks like +``` +["I am the first", empty × 14, "actually, i am the second"] +``` + +** Explanation ** + +This is how array's `.length` works. It takes index of the last elemnt, and returns `index+1`. + +Use native array methods to add items to it: `push`, `unshift`. + +— [@dogusev][1] + +[1]:https://github.com/dogusev \ No newline at end of file From fcd3b7f5ae5ad843ea333d93ccac802231a4ba58 Mon Sep 17 00:00:00 2001 From: Dmitriy Gusev Date: Thu, 21 Mar 2019 19:31:14 +0200 Subject: [PATCH 2/2] more example added --- .../md/2019-03-19-indexes-and-length-of-array.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/shared/md/2019-03-19-indexes-and-length-of-array.md b/src/shared/md/2019-03-19-indexes-and-length-of-array.md index a43f2cb0..ea5081fd 100644 --- a/src/shared/md/2019-03-19-indexes-and-length-of-array.md +++ b/src/shared/md/2019-03-19-indexes-and-length-of-array.md @@ -9,13 +9,23 @@ Lets create an empty array, and check its length is `0` Lets add something to its first place: ``` + var arr = [] arr[0] = 'I am the first'; arr.length; // 1 ``` Oh, what if... + +``` + var arr = [] + arr[3] = 'I am the first'; + arr.length; // 4 ``` + +``` + var arr = [] + arr[0] = 'I am the first'; arr[15] = 'actually, i am the second'; arr.length; // 16 ```