<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kei Cheng on Medium]]></title>
        <description><![CDATA[Stories by Kei Cheng on Medium]]></description>
        <link>https://medium.com/@keicheng?source=rss-29c3a56bd01c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R8auRdVte2XRrE4574AfXA.jpeg</url>
            <title>Stories by Kei Cheng on Medium</title>
            <link>https://medium.com/@keicheng?source=rss-29c3a56bd01c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:51:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@keicheng/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Javascript 取得 Object 屬性資料]]></title>
            <link>https://medium.com/@keicheng/javascript-%E5%8F%96%E5%BE%97-object-%E5%B1%AC%E6%80%A7%E8%B3%87%E6%96%99-2d0e4b6b9dc1?source=rss-29c3a56bd01c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d0e4b6b9dc1</guid>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[property]]></category>
            <dc:creator><![CDATA[Kei Cheng]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 06:00:13 GMT</pubDate>
            <atom:updated>2023-02-26T06:41:40.429Z</atom:updated>
            <content:encoded><![CDATA[<p>在 Object 中雖然有 entries, keys, values 可取得物件中的屬性與值，若屬性被設定為不可列舉的情況下，則無法被取出。</p><pre>let obj = {<br>  a: 1,<br>  b: 2,<br>  c() {<br>    return &#39;Hello&#39;  <br>  }<br>};<br><br>Object.defineProperty(obj, &#39;d&#39;, {<br>  value: 4,<br>  enumerable: false<br>});<br><br>console.log(Object.keys(obj));<br>// [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;] =&gt; d 設為不可列舉，所以透過 keys 無法取得。</pre><h3>Object.getOwnPropertyNames(obj)</h3><p>透過這個方法就能取得所有可列舉與不可列舉的屬性名，但不包含 Symbol 值作為屬性名。</p><p>陣列也可以使用這個方法，回傳的會是一組索引值的陣列以及陣列自身屬性 length。</p><pre>console.log(Object.getOwnPropertyNames(obj));<br>// [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]<br><br>var arr = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;];<br>console.log(Object.getOwnPropertyNames(arr));<br>// [&quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;length&quot;]</pre><p>也能透過這個方法取得函式物件裡的屬性。</p><pre>function Say() {<br>  this.voice = 5;<br>  this.method = function() {};<br>}<br><br>console.log(Object.getOwnPropertyNames(Say));<br>// [&#39;length&#39;, &#39;name&#39;, &#39;arguments&#39;, &#39;caller&#39;, &#39;prototype&#39;]<br><br>console.log(Object.getOwnPropertyNames(new Say));<br>// [&#39;voice&#39;, &#39;method&#39;]</pre><p>那麼 for…in, Object.keys() 與 Object.getOwnPropertyNames() 這三種方法的區別是什麼呢？</p><ul><li>for…in 可列出自身與繼承物件的所有可被列舉屬性</li><li>Object.keys() 僅可列出自身並且可被列舉的屬性</li><li>Object.getOwnPropertyNames 可列出自身的所有屬性，但不包含 Symbol 作為屬性名的部分</li></ul><pre>let parent = Object.create(Object.prototype, {<br>  lastName: {<br>    value: &#39;Guo&#39;,<br>    writable: true,<br>    enumerable: true,<br>    configurable: true<br>  },<br>  isRich: {<br>    value: true,<br>    writable: true,<br>    enumerable: false,<br>    configurable: true<br>  }<br>});<br><br>let child = Object.create(parent, {<br>  gender: {<br>    value: &#39;female&#39;,<br>    writable: true,<br>    enumerable: true,<br>    configurable: true<br>  },<br>  weight: {<br>    value: 20,<br>    writable: true,<br>    enumerable: false,<br>    configurable: true<br>  }<br>});<br><br>for (var key in child) {<br>  console.log(key)<br>}<br>// gender =&gt; 自身可被列舉的屬性<br>// lastName =&gt; 父層物件可被列舉的屬性<br>// weight 與 isRich 因為 enumerable 設為 false 不能被列舉，因此都不會被遍歷<br><br>for (var key in child) {<br>  if (child.hasOwnProperty(key)) {<br>    console.log(key);<br>  }<br>}<br>// gender =&gt; 可透過 hasOwnProperty 來過濾原型鍊繼承的屬性<br><br>console.log(Object.keys(child));<br>// [&#39;gender&#39;] =&gt; 僅列出自身可被列舉的屬性<br><br>console.log(Object.getOwnPropertyNames(child));<br>// [&#39;gender&#39;, &#39;weight&#39;]=&gt; 可列出自身所有屬性</pre><h3>Object.getOwnPropertySymbols(obj)</h3><p>getOwnPropertyNames 無法取得以 Symbol 值作為屬性名，這個方法可取得一組 Symbol 屬性的陣列。</p><pre>let obj = {};<br>let a = Symbol(&#39;a&#39;);<br>let b = Symbol.for(&#39;b&#39;);<br><br>obj[a] = &#39;I`m a&#39;;<br>obj[b] = &#39;I`m b&#39;;<br><br>console.log(Object.getOwnPropertySymbols(obj))<br>// [Symbol(a), Symbol(b)]</pre><h3>Object.getOwnPropertyDescriptor(obj, prop)</h3><p>此方法可以取得屬性的各種設定。</p><pre>let person = {};<br><br>Object.defineProperty(person, &#39;firstName&#39;, {<br>  value: &#39;Kei&#39;,<br>  enumerable: true<br>});<br><br>Object.defineProperty(person, &#39;lastName&#39;, {<br>  value: &#39;Cheng&#39;<br>});<br><br>let descriptor = Object.getOwnPropertyDescriptor(person, &#39;firstName&#39;);<br>console.log(descriptor);<br>// {value: &#39;Kei&#39;, writable: false, enumerable: true, configurable: false}<br>// 即便只設定 enumerable，但其他預設的配置也會全部顯示出來</pre><h3>Object.getOwnPropertyDescriptors(obj)</h3><p>當物件有眾多屬性時，若要查找全部屬性的配置，就可以這麼用。</p><pre>let descriptors = Object.getOwnPropertyDescriptors(person);<br>console.log(descriptors);<br>/*<br>{<br>  firstName: {value: &#39;Kei&#39;, writable: false, enumerable: true, configurable: false}<br>  lastName: {value: &#39;Cheng&#39;, writable: false, enumerable: false, configurable: false}<br>}<br>*/</pre><h3>Object.prototype.hasOwnProperty()</h3><p>判斷物件是否擁有某個屬性，會回傳 true / false</p><pre>console.log(person.hasOwnProperty(&#39;firstName&#39;));<br>// true<br><br>console.log(person.hasOwnProperty(&#39;fullName&#39;));<br>// false</pre><h3>Object.hasOwn(obj, prop)</h3><p>也可以透過 hasOwn() 判斷是否擁有某個屬性，這個方法跟 hasOwnProperty 是一樣的，甚至是用來取代 hasOwnProperty。</p><pre>console.log(Object.hasOwn(person, &#39;firstName&#39;));<br>// true<br><br>console.log(Object.hasOwn(person, &#39;lastName&#39;));<br>// false</pre><p>要注意一點的是，即使屬性裡的值是 null 或 undefined，也都會回傳 true。因為物件裡的屬性值可以存放任何型別的資料，包含函式。除非 delete 這個屬性。</p><pre>person.say = null;<br>console.log(Object.hasOwn(person, &#39;say&#39;));<br>// true<br><br>delete person.say;<br>console.log(Object.hasOwn(person, &#39;say&#39;));<br>// false</pre><p>另外每個物件雖然會通過原型鍊繼承幾種屬性，但是使用 hasOwn 或 hasOwnProperty 這兩種方法都會回傳 false。只能判斷物件自身的屬性。</p><pre>console.log(Object.hasOwn(person, &#39;toString&#39;));<br>// false<br><br>console.log(&#39;toString&#39; in person);<br>// true =&gt; 但可以透過這個方式去尋找原型鍊繼承的屬性與方法</pre><p>如果是函式物件或陣列也都能透過這兩種方法去判斷是否擁有屬性。如果是陣列，要把索引值作為屬性名帶入。</p><pre>function Person() {<br>    this.firstName = &#39;&#39;;<br>    this.lastName = &#39;&#39;<br>}<br><br>let kei = new Person();<br>Object.hasOwn(kei, &#39;firstName&#39;);<br>// true<br><br>const fruits = [&#39;Apple&#39;, &#39;Banana&#39;,&#39;Watermelon&#39;, &#39;Orange&#39;];<br>Object.hasOwn(fruits, 3);   // true =&gt; Orange<br>Object.hasOwn(fruits, 4);   // false =&gt; 沒有被定義</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d0e4b6b9dc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Object freeze, seal 與 preventExtensions]]></title>
            <link>https://medium.com/@keicheng/javascript-object-freeze-seal-%E8%88%87-preventextensions-8564abff9a14?source=rss-29c3a56bd01c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8564abff9a14</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[assign]]></category>
            <category><![CDATA[preventextension]]></category>
            <category><![CDATA[freez]]></category>
            <category><![CDATA[seal]]></category>
            <dc:creator><![CDATA[Kei Cheng]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 11:30:49 GMT</pubDate>
            <atom:updated>2023-02-25T11:30:49.536Z</atom:updated>
            <content:encoded><![CDATA[<p>針對物件中某個屬性設置不能修改、不能刪除、不能設置，可透過 defineProperty 或 defineProperties 兩種方法可以達成。</p><p>若是要針對整個物件做鎖定，可使用 freeze, seal 以及 preventExtensions 三種方法可以達到，那麼這三種方法的差異是什麼？</p><p>可新增屬性可刪除屬性可修改屬性preventExtensions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*s-396nJ_x9gsgVvHko3bmg.png" /><figcaption>freeze, seal, preventExtensions 的差異</figcaption></figure><h3>freeze</h3><p>如字面上所說就是凍結。不能新增屬性、不能刪除屬性，也不能修改屬性。就如同 configable 被設置為 false 一樣。</p><p><strong>使用方式：Object.freeze(obj)</strong></p><p>被凍結後的物件無法被操作，但僅限於子層屬性。若屬性中的值是物件、陣列等非基本型別，依然可以操作。</p><pre>let obj = {<br>  a: 1,<br>  b: 2,<br>  c: {}<br>};<br>Object.freeze(obj);<br><br>obj.a = 2;<br>console.log(obj);<br>// {a: 1, b: 2, c: {}} =&gt; a 依然是 1 無法被覆寫<br><br>delete obj.a; // false =&gt; 無法刪除<br>console.log(obj);<br>// {a: 1, b: 2, c: {}}<br><br>obj.d = 4;<br>console.log(obj);<br>// {a: 1, b: 2, c: {}} =&gt; 無法新增<br><br>obj.c.say = &#39;Hello&#39;;<br>console.log(obj);<br>// {a: 1, b: 2, c: {say: &#39;Hello&#39;}}<br>// obj.c 是一個物件，可以新增、修改、刪除，不受 freeze 影響<br></pre><p>若是要判斷一個物件是否被凍結，可使用 Object.isFrozen()。若被凍結會回傳 true，相反則 false。</p><pre>console.log(Object.isFrozen(obj));<br>// true<br><br>console.log(Object.isSealed(obj));<br>// true，不能覆寫、刪除、新增，等同被封閉<br><br>console.log(Object.isExtensible(obj));<br>// false =&gt; 不能擴充所以回傳 false</pre><h3>seal</h3><p>將物件封閉起來，不能新增屬性、不能刪除屬性，但已有的屬性是可以修改的。無法修改屬性數量，但可以更新其內容。</p><p><strong>使用方式：Object.seal(obj)</strong></p><pre>let obj = {<br>  a: 1,<br>  b: 2,<br>  c: {}<br>};<br>Object.seal(obj);<br><br>obj.a = 2;<br>console.log(obj);<br>// {a: 2, b: 2, c: {}} =&gt; a 可以被覆寫<br><br>delete obj.a; // false =&gt; 但是不能刪除<br>console.log(obj);<br>// {a: 1, b: 2, c: {}}<br><br>obj.d = 4;<br>console.log(obj);<br>// {a: 1, b: 2, c: {}} =&gt; 也無法新增<br><br>obj.c.say = &#39;Hello&#39;;<br>console.log(obj);<br>// {a: 1, b: 2, c: {say: &#39;Hello&#39;}}<br>// obj.c 是一個物件，可以新增、修改、刪除，不受 seal 影響</pre><p>若要判斷物件是否被封閉，可使用 Object.isSealed() 來判斷。若被封閉會回傳 true，相反的則回傳 false。</p><pre>console.log(Object.isSealed(obj));<br>// true<br><br>console.log(Object.isFrozen(obj));<br>// false =&gt; 還能被覆寫，不是被凍結<br><br>console.log(Object.isExtensible(obj));<br>// false =&gt; 不能擴充所以回傳 false</pre><h3>preventExtensions</h3><p>如字面上一樣防止擴充。所以除了新增屬性之外，可以刪除、可以修改。</p><p><strong>使用方式：Object.preventExtensions(obj)</strong></p><pre>let obj = {<br>  a: 1,<br>  b: 2,<br>  c: {}<br>};<br>Object.preventExtensions(obj);<br><br>obj.a = 2;<br>console.log(obj);<br>// {a: 2, b: 2, c: {}} =&gt; a 可以被覆寫<br><br>delete obj.a; // false =&gt; 可以刪除<br>console.log(obj);<br>// {b: 2, c: {}}<br><br>obj.d = 4;<br>console.log(obj);<br>// {b: 2, c: {}} =&gt; 但無法擴充所以不能新增<br><br>obj.c.say = &#39;Hello&#39;;<br>console.log(obj);<br>// {b: 2, c: {say: &#39;Hello&#39;}}<br>// obj.c 是一個物件，可以新增、修改、刪除，不受 preventExtensions 影響</pre><p>若要判斷物件是否可以擴充，可使用 Object.isExtensible()。若可以擴充則回傳 true，相反的則回傳 false。這裡提及的單純只是是否能擴充，如果物件被設置了 freeze 或 seal，因為都無法新增屬性，因此判斷是否能擴充時都會回傳 false。</p><pre>console.log(Object.isExtensible(obj));<br>// false =&gt; 因為被設置了 preventExtensions<br><br>console.log(Object.isFrozen(obj));<br>// false =&gt; 還能被覆寫，不是被凍結<br><br>console.log(Object.isSealed(obj));<br>// false =&gt; 可以修改、刪除，不是被封閉</pre><p>無論使用 freeze, seal 或 preventExtensions，只要設置了就無法解除，使用前要注意這點。不過有一個方法可以解除，透過 Object.assign() 來 clone 一份成為新的物件，覆蓋原有變數就能達到解除的作用。但若使用 const 設置一個常數，那就掰掰了。</p><pre>let obj = {<br>  a: 1,<br>  b: 2,<br>  c: {}<br>};<br>Object.freeze(obj);<br>console.log(Object.isFrozen(obj)); // true<br><br>obj = Object.assign({}, obj);<br>console.log(Object.isFrozen(obj)); // false<br><br>// 如果用 const obj = {} 那就連 assign 也無法解除了</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8564abff9a14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Object Entries]]></title>
            <link>https://medium.com/@keicheng/javascript-object-entries-aa98b0a1e2e4?source=rss-29c3a56bd01c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa98b0a1e2e4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[values]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[keys]]></category>
            <category><![CDATA[objects]]></category>
            <dc:creator><![CDATA[Kei Cheng]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 10:00:25 GMT</pubDate>
            <atom:updated>2023-02-25T10:08:36.417Z</atom:updated>
            <content:encoded><![CDATA[<p>透過 Object.entries() 取得可列舉的所有屬性與值。每一組 key-value pair 會成為一組陣列，並且將所有陣列再共同存入一組陣列，最後回傳一份二維陣列。</p><p><strong>使用方式：Object.entries(obj)</strong></p><pre>const person = {<br>  firstName: &#39;Kei&#39;,<br>  lastName: &#39;Cheng&#39;,<br>  fullName() {<br>    return `${this.firstName} ${this.lastName}`<br>  }<br>};<br><br>console.log(Object.entries(person));<br>// [[&#39;firstName&#39;, &#39;Kei&#39;], [&#39;lastName&#39;, &#39;Cheng&#39;], [&#39;fullName&#39;, function()]]<br><br>for (const [key, value] of Object.entries(person)) {<br>  console.log(`${key}: ${value}`);<br>}<br>/*<br>firstName: Kei<br>lastName: Cheng<br>fullName: fullName() {<br>  return `${this.firstName} $(this.lastName}`<br>}<br>*/</pre><p>這個方法可快速從 object 轉成 map</p><pre>let map = new Map(Object.entries(person));<br>console.log(map);<br>// Map(3) {&#39;firstName&#39; =&gt; &#39;Kei&#39;, &#39;lastName&#39; =&gt; &#39;Cheng&#39;, &#39;fullName&#39; =&gt; ƒ}</pre><h3>values</h3><p>如果只要取得所有屬性值，可使用 Object.values()。同樣的只能取出可列舉的屬性值。</p><p><strong>使用方法：Object.values(obj);</strong></p><pre>console.log(Object.values(person));<br>// [&#39;Kei&#39;, &#39;Cheng&#39;, ƒ]</pre><h3>keys</h3><p>可以取出值，那麼也可以取出屬性。同樣也只能取出可列舉的屬性。</p><p><strong>使用方法：Object.keys(obj);</strong></p><pre>console.log(Object.keys(person));<br>// [&#39;firstName&#39;, &#39;lastName&#39;, &#39;fullName&#39;]</pre><p>物件可使用的迴圈方法沒有陣列來的方便，物件通常只能使用 for…in 遍歷物件內所有資料。若透過以上三種方法取得陣列資料後可做更方便的陣列方法，例如 forEach, filter, reduce 等等。</p><p>另外物件也沒有 length 這個屬性，如果要取得物件內有多少組 key-value pair，也可以透過這三種方法來取得資料長度。</p><p>如果 Object 可透過這些方法轉為 Array 與 Map ，那麼 Array 與 Map 也可轉回 Object 嗎？跑迴圈重建物件當然是沒問題的，但還有一種方法可做到。</p><h3>fromEntries</h3><p>將 key-value 為陣列的資料表轉為物件</p><p><strong>使用方式：Object.fromEntries(obj)</strong></p><p>在 entries 範例中會將 key-value 轉為二維陣列，相同的也可透過 fromEntries 再轉回物件。</p><pre>let kei = Object.fromEntries([[&#39;firstName&#39;, &#39;Kei&#39;], [&#39;lastName&#39;, &#39;Cheng&#39;], [&#39;fullName&#39;, function()]]);<br>console.log(kei);<br>// {firstName: &#39;Kei&#39;, lastName: &#39;Cheng&#39;, fullName: ƒ}<br>// kei.fullName =&gt; Kei Cheng</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa98b0a1e2e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Object defineProperty]]></title>
            <link>https://medium.com/@keicheng/javascript-object-defineproperty-c3b5bed8dc82?source=rss-29c3a56bd01c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3b5bed8dc82</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[objects]]></category>
            <dc:creator><![CDATA[Kei Cheng]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 13:13:17 GMT</pubDate>
            <atom:updated>2023-02-25T11:39:24.885Z</atom:updated>
            <content:encoded><![CDATA[<p>平常建立新物件透過物件實字或物件建構式之後，可以隨時新增新的屬性與值來增加物件內容。</p><pre>const obj1 = {<br>  name: &#39;Kei&#39;<br>};<br>obj1.age = 30;<br><br>const obj2 = new Object();<br>obj2.name = &#39;Kei&#39;;<br>obj2.age = 30;</pre><p>defineProperty 則是第三種定義屬性的方法。</p><p><strong>使用方式：Object.defineProperty(obj, prop, descriptor);</strong></p><ul><li>obj: 必填。物件對象。</li><li>prop: 必填。需要定義或修改的屬性名稱，也可以是 Symbol。</li><li>descriptor: 必填。設置屬性值。</li></ul><pre>const obj3 = {};<br>Object.defineProperty(obj3, &#39;name&#39;, {<br>  value: &#39;Kei&#39;,<br>  configurable: false,<br>  writable: false,<br>  enumable: false,<br>  get() {},<br>  set() {}<br>});<br><br>// 其實就差不多是 obj3.name = &#39;Kei&#39;，value 就是該屬性的值。</pre><p>明明可以很簡單的新增或修改屬性，那為何要搞得這麼複雜呢？重點就在於對於屬性值的設置。一般來說透過物件實字或物件建構式產生的物件，在新增屬性之後都可以對其屬性內容任意修改、刪除值。如果要保護其內容不被更動的情況下，可以透過 defineProperty 來設定。</p><p>先來看 descriptor 裡有哪些配置：</p><p><strong>value</strong>: 屬性值。預設值為 undefined。<br>可以是任何值，包含字串、數字、函式、陣列、物件等等。</p><pre>let obj = {};<br>Object.defineProperty(obj, &#39;name&#39;, {});<br>console.log(obj); // {name: undefined}<br><br>Object.defineProperty(obj, &#39;name&#39;, {<br>  value: &#39;Kei&#39;<br>});<br>console.log(obj); // {name: &#39;Kei&#39;}</pre><p><strong>writable</strong>: 屬性值是否可以被覆寫。預設值為 false。<br>若設置 true 可以被覆寫，相反的 false 則不能覆寫。也就是說透過 defineProperty 設置的屬性值在沒有設定的情況下是不能覆寫的。</p><pre>let obj = {};<br>Object.defineProperty(obj, &#39;name&#39;, {<br>  value: &#39;Kei&#39;,<br>  writable: false<br>});<br>console.log(obj); // {name: &#39;Kei&#39;} =&gt; 因為不能複寫，所以沒有被改變。<br><br>Object.defineProperty(obj, &#39;name&#39;, {<br>  value: &#39;Kei&#39;,<br>  writable: true<br>});<br>obj.name = &#39;Jin&#39;;<br>console.log(obj); // {name: &#39;Jin&#39;}</pre><p><strong>enumerable</strong>: 是否可以被列舉，預設為 false。<br>當透過 for…in 或 Object.keys() 取得屬性時，是否會被列舉。</p><p>另外可使用 propertyIsEnumerable 方法來判斷該屬性是否能被列舉。</p><pre>let obj = {};<br>Object.defineProperty(obj, &#39;name&#39;, {<br>  value: &#39;Kei&#39;,<br>  enumerable: false<br>});<br>console.log(Object.keys(obj)); // [] =&gt; 因為不能列舉，所以不會顯示 name 這個屬性。<br>console.log(obj.propertyIsEnumerable(&#39;name&#39;)); // false<br><br>Object.defineProperty(obj, &#39;name&#39;, {<br>  value: &#39;Kei&#39;,<br>  enumerable: true<br>});<br>console.log(Object.keys(obj)); // [&#39;name&#39;]<br>console.log(obj.propertyIsEnumerable(&#39;name&#39;)); // true</pre><p><strong>configurable</strong>: 是否可設置特性。預設為 false。<br>這個設置較為複雜，若是設為 false 之後，這個屬性值就無法被刪除、不能被修改配置。即便要重新設定為 true 也無法再更改，因此初始沒有設置或是設定為 false 之後就等同於這個屬性都無法再設置，這點要注意。</p><pre>let obj = {};<br>Object.defineProperty(obj, &#39;name&#39;, {<br>  value: &#39;Kei&#39;,<br>  configurable: false<br>});<br><br>delete obj.name; // false<br>console.log(obj.name); // &#39;Kei&#39; 不能被修改，所以 name 還保留著<br><br>Object.defineProperty(obj, &#39;name&#39;, {<br>  configurable: true<br>});<br>// 即使後續再改成 true，這時候會出現：Cannot redefine property: name</pre><p>以上配置可以得知</p><pre>let obj = {};<br>obj.age = 30;<br>// 等同於<br>Object.defineProperty(obj, &#39;age&#39;, {<br>  value: 30,<br>  writable: true,<br>  configurable: true,<br>  enumerable: true<br>});</pre><p><strong>get()</strong>: 屬性的 getter 函式。預設為 undefined。<br>可透過此函式取得屬性值。使用此函式之後因為都會與 value 一樣回傳屬性值，因此不能同時使用 value 與 getter，否則會回傳錯誤訊息。</p><pre>Object.defineProperty(obj, &quot;conflict&quot;, {<br>  value: 0x9f91102,<br>  get() { return 0xdeadbeef; }<br>});<br>// Invalid property descriptor. Cannot both specify accessors and a value or writable attribute</pre><pre>const person = {<br>  firstName: &#39;Kei&#39;,<br>  lastName: &#39;Cheng&#39;<br>};<br><br>Object.defineProperty(person, &#39;fullName&#39;, {<br>  get() {<br>    return this.firstName + &#39; &#39; + this.lastName;<br>  }<br>});<br>console.log(person.fullName); // Kei Cheng</pre><p>set(): 屬性的 setter 函式。預設為 undefined。<br>當屬性重新賦予值時就會觸發這個函式。</p><pre>Object.defineProperty(person, &#39;age&#39;, {<br>  get() { return this._age || 40; },<br>  set(value) { return this._age = value &lt;= 40 ? value : 40; }<br>});<br>console.log(person.age); // 40<br>person.age = 50;<br>console.log(person.age); // 40</pre><p>Vue 2.x 的核心方法其實就是 defineProperty。</p><p>Vue.js 採用的數據驅動，Watcher 到 Observe 之間的動作就是通過 Object.defineProperty() 來攔截每個屬性的 getter 與 setter。在資料變動時發布給 Watcher，觸發相對應的監聽。</p><p>更詳細的 Vue 原理可參考：<br><a href="https://segmentfault.com/a/1190000006599500">https://segmentfault.com/a/1190000006599500</a></p><h3>defineProperties</h3><p>這個方法其實跟 Object.defineProperty() 幾乎相同，差別在於 defineProperty 每次只能設置一個屬性，而 defineProperties 可以同時設置多個屬性。</p><p>使用方式：Object.defineProperties(obj, props);</p><ul><li>obj: 必填。物件對象。</li><li>props: 必填。定義多個屬性。</li></ul><pre>var obj = {};<br>Object.defineProperties(obj, {<br>  firstName: {<br>    value: &#39;Kei&#39;,<br>    writable: true<br>  },<br>  lastName: {<br>    value: &#39;Cheng&#39;,<br>    writable: true<br>  },<br>  fullName: {<br>    get() {<br>      return `${this.firstName} ${this.lastName}`;<br>    }<br>  }<br>});<br><br>console.log(obj.fullname); // &#39;Kei Cheng&#39;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3b5bed8dc82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Object Create]]></title>
            <link>https://medium.com/@keicheng/javascript-object-create-ed0e637897fd?source=rss-29c3a56bd01c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed0e637897fd</guid>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[create]]></category>
            <dc:creator><![CDATA[Kei Cheng]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 07:46:50 GMT</pubDate>
            <atom:updated>2023-02-22T07:46:50.521Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>使用方式：Object.create(proto[, propertiesObject])</strong></p><ul><li>proto: 指定新物件的原型</li><li>propertiesObject: 非必要。可自定義屬性、屬性值以及屬性設定，會加進新創建的物件當中。</li></ul><p>過去建立物件時通常使用物件實字或物件建構式，尤其前者較為方便。</p><pre>let o1 = {}; // 物件實字<br>let o2 = new Object(); // 物件建構式</pre><p>雖說 Object.create() 也能夠創建新物件，但與物件實字、物件建構式概念上是不同的。create 的第一個參數其實是 proto 而不是物件，這時候先來複習一下原型鍊：</p><pre>console.log(o1.__proto__ === Object.prototype) // true<br>console.log(o2.__proto__ === Object.prototype) // true<br><br>let o3 = Object.create({});<br>console.log(o3.__proto__ === Object.prototype) // false</pre><p>o3 的例子中其實是創建一個新物件，並且它的原型繼承來自空物件，因此 o3 的上層其實是那個空物件，因此第一個參數是 proto 而非 source。這就是跟物件實字、物件建構式不一樣的地方。如果想要建立一個新物件並且繼承某個物件，create 是合適的方法。</p><pre>const Person = {<br>  firstname: &#39;&#39;,<br>  lastname: &#39;&#39;,<br>  log() {<br>    console.log(`My name is ${this.firstname} ${this.lastname}`);<br>  }<br>};<br><br>let kei = Object.create(Person, {<br>  gender: {<br>    value: &#39;male&#39;<br>  }<br>});<br>kei.firstname = &#39;Kei&#39;;<br>kei.lastname = &#39;Cheng&#39;;<br>kei.log(); // My name is Kei Cheng<br><br>console.log(kei.__proto__ === Person.prototype)<br>// false ㄟ 怎麼這樣<br><br>console.log(kei.__proto__ === Person)<br>// true，這又是怎麼回事？<br><br>console.log(kei.__proto__.__proto__ === Object.prototype) // true</pre><p>create 的做法可以想像成先建立一個空物件，然後將這個空物件的 __proto__ 指向到 Person</p><pre>let jin = {};<br>jin.__proto__ = Person;<br>// 以上這兩行就等同 let jin = Object.create(Person);<br><br>jin.firstname = &#39;Jinjin&#39;;<br>jin.lastname = &#39;Hsu&#39;;<br>jin.log(); // My name is Jinjin Hsu<br><br>// 如此<br>function Constructor() {}<br>var o4 = new Constructor();<br>// 等同於:<br>var o4 = Object.create(Constructor.prototype);<br><br>var o5 = {};<br>// 等同於:<br>var o5 = Object.create(Object.prototype);</pre><h4>用 create 實現繼承</h4><pre>// Shape - 父類別<br>function Shape() {<br>  this.x = 0;<br>  this.y = 0;<br>}<br><br>// 父類別的方法<br>Shape.prototype.move = function(x, y) {<br>  this.x += x;<br>  this.y += y;<br>  console.info(&#39;Shape moved.&#39;);<br>};<br><br>// Rectangle - 子類別<br>function Rectangle() {<br>  Shape.call(this); // call super constructor.<br>}<br><br>Rectangle.prototype = Object.create(Shape.prototype);<br>Rectangle.prototype.constructor = Rectangle;<br><br>var rect = new Rectangle();<br><br>console.log(rect instanceof Rectangle);// true<br>console.log(rect instanceof Shape);// true<br>rect.move(1, 1); // Outputs, &#39;Shape moved.&#39;<br><br>// 範例來自 mdn</pre><h4>propertiesObject</h4><p>當透過 create 創建一個繼承某物件之後，也可以建立自己的屬性、屬性值及其屬性設定。propertiesObject 的作用相當於 Object.defineProperty()。</p><pre>let o = Object.create(Object.prototype, {<br>  foo: {<br>    value: &#39;hello&#39;,<br>    writable: false // 設定為 false 之後就無法被覆寫<br>  },<br>  bar: {<br>    configurable: false,<br>    get: function() { return 10; },<br>    set: function(value) { console.log(&#39;Setting `o.bar` to&#39;, value); }<br>  }<br>});<br><br>console.log(o.foo) // &#39;hello&#39;<br>console.log(o.bar) // 10<br><br>console.log(o)<br>/*<br>bar: (...)<br>foo: &quot;hello&quot;<br>get bar: ƒ ()<br>set bar: ƒ (value)<br>[[Prototype]]: Object<br>*/</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed0e637897fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Prototype]]></title>
            <link>https://medium.com/@keicheng/javascript-prototype-3ad440f97899?source=rss-29c3a56bd01c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ad440f97899</guid>
            <category><![CDATA[function]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[prototype-chain]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototype]]></category>
            <dc:creator><![CDATA[Kei Cheng]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 06:40:44 GMT</pubDate>
            <atom:updated>2023-02-26T06:18:16.023Z</atom:updated>
            <content:encoded><![CDATA[<p>Javascript 除了基本型別之外，其餘所有皆是物件。</p><p>當初 Brendan Eich 開發 Javascript 過程中，為了避免 JS 過於像是 C++ 繼承那樣複雜，因此 JS 一直都沒有 Class 可以使用，即便 ES6 的 Class 也只是語法糖並非是真正的 Class。但為了能將物件能夠串連起來，使用了 prototype 的概念將物件作繼承的動作。每當一個物件被建立時，同時也會自動生成 __proto__ 與 Constructor。</p><p>每當建立一個物件時，同時也會跟 Object 繼承屬性與方法。當中 __proto__ 就是與上層 Object 作為關聯的方式。而最頂級的 Object.__proto__ 則會是 null。</p><pre>var o1 = {};<br>console.log(o1);<br>/*<br>constructor: ƒ Object()<br>hasOwnProperty: ƒ hasOwnProperty()<br>isPrototypeOf: ƒ isPrototypeOf()<br>propertyIsEnumerable: ƒ propertyIsEnumerable()<br>toLocaleString: ƒ toLocaleString()<br>toString: ƒ toString()<br>valueOf: ƒ valueOf()<br>__defineGetter__: ƒ __defineGetter__()<br>__defineSetter__: ƒ __defineSetter__()<br>__lookupGetter__: ƒ __lookupGetter__()<br>__lookupSetter__: ƒ __lookupSetter__()<br>__proto__: Object<br>get __proto__: ƒ __proto__()<br>set __proto__: ƒ __proto__()<br>*/<br><br>console.log(o1.__proto__ === Object.prototype);<br>// true，o1 的上層即是 Object<br>console.log(o1.__proto__.__proto__); <br>// null，o1 的上層是最頂級的 Object，再上一層就不會有任何東西<br></pre><h4>從建構函式來看原型鍊</h4><p>當建立函式時是從 Function 去繼承，因此每次建立函式時都會有 constructor 與 __proto__ 兩個屬性。</p><pre>// constructor<br>function Person(name, age) {<br>  this.name = name;<br>  this.age = age;<br>  this.log = function () {<br>    console.log(this.name + &#39;, age:&#39; + this.age);<br>  }<br>}<br>console.log(Person.__proto__ === Function.prototype)<br>// true，Person 由 Function 繼承<br><br>console.log(Person.__proto__.__proto__ === Object.prototype)<br>// true，函式也是從物件繼承</pre><p>當要建立 Person 這個物件時，可以使用 new 這個關鍵字來建立物件。但這時候要注意的是被 new 出來的是物件，而不是函式了。</p><pre>var kei = new Person(&#39;Kei&#39;, 30);<br>console.log(kei.__proto__ === Person.prototype);<br>// true，從 Person 建立實例，所以 kei 的上層是 Person 這符合預期<br><br>console.log(kei.__proto__.__proto__ === Function.prototype);<br>// false，ㄟ ～怎麼上層不是 Function 了？<br><br>console.log(kei.__proto__.__proto__ === Object.prototype);<br>// true</pre><h4>new</h4><p>new 這個關鍵字用來建立實體時，會執行幾件事情：</p><ul><li>創建一個新物件，暫且稱為 o</li><li>把 o 的 __proto__ 指向到 Person.prototype 建立原型鍊</li><li>把 o 作為上下文呼叫 Person 這個建構函式</li><li>回傳 o</li></ul><pre>var o = new Object();<br><br>// 讓 o 繼承原型鍊<br>o.__proto__ = Person.prototype;<br><br>// 執行建構函式<br>Constructor.apply(o, arguments);<br><br>// 回傳建立好的物件<br>return o;</pre><p>所以無論是從哪裡 new 出一個新物件，上層的 __proto__ 都會是 Object.prototype</p><pre>let m = new Map();<br>console.log(a.__proto__ === Map.prototype) // true<br>console.log(a.__proto__.__proto__ === Object.prototype) // true</pre><h4>instanceof</h4><p>a instanceof b，用來判斷 a 是否為 b 的實例</p><pre>console.log(kei instanceof Person) // true<br>console.log(kei instanceof Object) // true<br>console.log(kei instanceof Function) // false</pre><p>這裡有一個特別的現象，Object 與 Function 互為實例。原因是 Object.prototype 本身也是建構函式，因此也會指向到 Function，這裡就是原型鍊最容易搞混淆的地方。</p><pre>console.log(Object.__proto__);<br>// ƒ () { [native code] }<br>// 可能會以為作為最頂級的 Object 的 __proto__ 會是 null<br>// 如果作為原型鍊的確是如此，若單一看 Object.__proto__<br>// 則是建構函式<br><br>console.log(Function instanceof Object); // true<br>console.log(Object instanceof Function); // true<br><br>// Function 的 __proto__ 會指向 Function.prototype<br>// 而 Function.prototype 的 __proto__ 會指向 Object.prototype<br>console.log(Function.__proto__ === Function.prototype); // true<br>console.log(Function.__proto__.__proto__ === Object.prototype); //true<br><br>// Object 的 __proto__ 會指向 Function.prototype<br>console.log(Object.__proto__ === Function.prototype); // true</pre><h3>Prototype</h3><pre>function Person(name, age) {<br>  this.name = name;<br>  this.age = age;<br>  this.log = function () {<br>    console.log(this.name + &#39;, age:&#39; + this.age);<br>  }<br>}</pre><p>上述 Person 範例中可以另外觀察到 name 與 age 在每一次實體化都會是不同的，但 log 這個方法做的事情相同，每個實體之間應該可以共享，這種情況就會佔兩份空間。為了讓建構函式可以共享方法，這時候就可以利用 prototype 來讓每個 Person 實例達成共享 log。</p><pre>function Person(name, age) {<br>  this.name = name;<br>  this.age = age;<br>}<br>  <br>Person.prototype.log = function () {<br>  console.log(this.name + &#39;, age:&#39; + this.age);<br>}<br><br>var kei = new Person(&#39;Kei&#39;, 30);<br>var jin = new Person(&#39;Jinjin&#39;, 30);<br>console.log(kei.log === jin.log) // true<br>// 此時 log 這個方法就會是 Person 的共享方法<br><br>console.log(kei.__proto__ === Person.prototype)<br>// true，kei 的上一層就會是 Person<br><br>console.log(kei.__proto__.__proto__ === Object.prototype);<br>// true，再上一層即是頂層的 Object，若再上一層就會顯示 null</pre><p>JS 原生物件也可以透過 prototype 去擴充或修改原生的方法，但是不建議這麼做。</p><pre>Array.prototype.last = function () {<br>    return this[this.length - 1];<br>};<br>  <br>console.log([1,2,3].last()) // 3</pre><h4>constructor</h4><p>每一個 prototype 都會有個 constructor。若是建構函式，原型中的 constructor 指的就是自己。</p><pre>// Person 的 constructor 就是 Person<br>console.log(Person.prototype.constructor === Person); // true<br>console.log(Person.prototype.hasOwnProperty(&#39;constructor&#39;)); // true</pre><h3>Object.getPrototypeOf(obj)</h3><p>透過這個方法可以取得物件的原型鍊來源。</p><pre>let obj1 = {};<br>console.log(Object.getPrototypeOf(obj1) === Object.prototype)<br>// true<br>// 每當透過物件實字或物件建構式建立一個物件都是從 Object.prototype 繼承原型鍊<br><br>let obj2 = Object.create(obj1);<br>console.log(Object.getPrototypeOf(obj2) === obj1);<br>// true<br><br>console.log(Object.getPrototypeOf(kei) === Person.prototype);<br>// true<br><br>console.log(Object.getPrototypeOf(Person) === Function.prototype);<br>// true</pre><h3>Object.setPrototypeOf(obj, prototype)</h3><p>物件的原型鍊是可以被更改的，但是不建議使用這個方法。更改原型鍊對 JS 引擎來說是一項很慢的操作。如果要改變物件原型鍊的新對象，建議使用 Object.create()</p><pre>class Human {}<br>class SuperHero {}<br><br>Object.setPrototypeOf(SuperHero.prototype, Human.prototype);<br>// 範例來自 mdn 文件</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ad440f97899" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Object Assign]]></title>
            <link>https://medium.com/@keicheng/javascript-object-assign-973a4e701cdc?source=rss-29c3a56bd01c------2</link>
            <guid isPermaLink="false">https://medium.com/p/973a4e701cdc</guid>
            <category><![CDATA[assign]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kei Cheng]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 00:42:54 GMT</pubDate>
            <atom:updated>2023-02-22T00:43:48.067Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>使用方式：Object.assign(target, sources…)</strong></p><p>將一個或多個物件合併至目標對象，也可以將合併結果存入新變數當中，但這個行為只會將 target 存於 stack 中的資料位址複製給新變數，屬於淺拷貝。如果來源物件有重複的屬性，後者來源內容會覆蓋前者以及目標對象。</p><pre>const target = { a: 1, b: 2 };<br>const source1 = { b: 4, c: 5 };<br>const source2 = { a: 2, d: 100}<br><br>const returnedTarget = Object.assign(target, source1, source2);<br>// { a: 2, b: 4, c: 5, d: 100 }<br><br>console.log(target === returnedTarget);<br>// true，因為是同一個資料位址所以會是同一個東西<br><br>returnedTarget.a = 23;<br>console.log(target.a);<br>// 23</pre><p>assign 很常用於複製物件，但剛剛上述範例中表示會以淺拷貝方式到新變數當中，為了避免這樣的情形，可以直接將 target 設立一個物件實字，相當等於建立一個新物件再複製其他物件過來。但要注意的是這個方法只能用於子層 value 為基本型別的情況，若 value 為物件或陣列，依然會是複製原有的 reference。</p><pre>let obj1 = { a: 0 , b: { c: 0}};<br>let obj2 = { a: 1, d: 3};<br>let copy1 = Object.assign(obj1, obj2);<br>console.log(copy1)<br>// {a: 1, b: { c: 0}, d: 3}<br>// 重複的屬性將會覆蓋目標物件<br><br>obj1.a = 2;<br>console.log(copy1);<br>// {a: 2, b: { c: 0}, d: 3}<br>// a 也會跟著變 2<br>console.log(obj1 === copy1)<br>// true，因為還是同一個記憶體位址<br><br>let copy2 = Object.assign({}, obj1);<br>obj1.a = 3;<br>console.log(copy2);<br>// {a: 2, b: { c: 0}, d: 3}<br>console.log(copy2 === obj1);<br>// 因為是建立一個新物件再複製，因此會建立一個新記憶體位址儲存內容，copy2 已經與 obj1 無關<br><br>obj1.b.c = 1;<br>console.log(copy2);<br>// { a: 1 , b: { c: 1}};<br>console.log(copy2.b === obj1.b);<br>// true 當值為物件時只會複製記憶體的位址而不是創建新的資料，所以 obj1.b.c 更動時，copy2.b.c 也會跟著更動。</pre><p>這牽涉到 JS 引擎在記憶體使用方式。JS 在記憶體空間區分代碼區與數據區。數據區又區分 stack 與 heap。JS 基本型別的資料會直接存入 Stack 當中，而像物件這樣的複合型別會存入 heap 裡，但會把 heap 的記憶體位址存到 stack。每當變數存入的物件其實存入的是物件在記憶體中的位址，而不是只接指向 heap 。平常複製物件、陣列這類的複合資料，只是複製一份記憶體位址，而不是資料本身，才會有 a 變動 b 也會同步變動的情形。</p><p>每當物件中某個 value 也是物件時，這時也會將資料存放於 heap 中，stack 只是紀錄 heap 的位址。複製這個 value 時其實也只是複製了 stack 的位址。</p><h4>字串與陣列會被封裝成物件</h4><p>如果來源對象為陣列，則陣列中的索引會轉成屬性，而陣列元素轉成值變成一個物件合併到目標對象上。字串會先逐一將字符轉成陣列再轉成物件。</p><pre>let arr = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;];<br>let str = &#39;Hello&#39;;<br><br>let obj1 = Object.assign({}, arr);<br>console.log(obj1); // {0: &#39;A&#39;, 1: &#39;B&#39;, 2: &#39;C&#39;}<br><br>let obj2 = Object.assign({}, str);<br>console.log(obj2); // {0: &#39;H&#39;, 1: &#39;e&#39;, 2: &#39;l&#39;, 3: &#39;l&#39;, 4: &#39;o&#39;}<br><br>// 這裡要注意一點是物件的屬性雖然多為字串，但其實也能用數字。<br>// 提取物件內容時就不能使用 . 而要使用 []<br>obj2.0; // 這樣會顯示錯誤<br>obj2[0]; // &#39;H&#39;</pre><h4>中斷執行</h4><p>當 assign 在執行中途中如遇到錯誤，拷貝會停留於錯誤的項目中。在此之前的屬性會完成拷貝，但發生錯誤的屬性則不會。</p><p>例如目標對象中某個屬性被設定成無法改寫時，就會發生這種狀況。</p><pre>const target = Object.defineProperty({}, &#39;foo&#39;, {<br>  value: 1,<br>  writable: false<br>});<br>// 目標來源的 foo 屬性已被設置成只能讀取<br><br>Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });<br>// 當來源內容也有 foo 時，則會發生錯誤<br><br>console.log(target.bar);  // 2, 還沒發生錯誤所以成功了<br>console.log(target.foo2); // 3, 還沒發生錯誤所以成功了<br>console.log(target.foo);  // 1, foo 不會被覆寫因此停留在這.<br>console.log(target.foo3); // 因為停留在 foo 這裡就不會被拷貝<br>console.log(target.baz);  // 因為停留在 foo 這裡就不會被拷貝</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=973a4e701cdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Array 陣列]]></title>
            <link>https://medium.com/@keicheng/javascript-array-%E9%99%A3%E5%88%97-a5abb68ae337?source=rss-29c3a56bd01c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5abb68ae337</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Kei Cheng]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 11:35:27 GMT</pubDate>
            <atom:updated>2023-02-21T17:43:38.505Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>一種直線式且連續性記憶體空間的資料結構。</li><li>每一筆資料可儲存的型別並不限制，可以是字串、數字、布林值、null、undefined、陣列、函式、物件等等。</li><li>陣列中有索引(index)，索引由 0 開始。可透過索引取得對應的儲存位址取得資料。</li><li>可以是一維陣列或是多維陣列。二維陣列對應於數學的矩陣概念<strong>。</strong></li><li>讀取與修改效率高，但刪除與新增元素效率差，因為需要移動大量資料。</li></ul><h4>如何建立 Array</h4><p>建立陣列可使用陣列實字或建構式建立。當使用陣列實字建立陣列時，輸入的參數只會被當作資料元素。如果透過建構式建立陣列，多筆資料時視為多筆元素建立到陣列當中；若只有單一數字作為參數，則當作陣列長度建立陣列資料。</p><pre>// Array Literal 陣列實字，最常見也是最簡單的方式。<br>// 可直接給予空陣列，或事先提供資料到陣列當中。<br>const arr1 = []; // []<br>const arr2 = [5]; //[5]<br>const arr3 = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;];<br><br>// 也可透過建構式建立陣列，但效率較差<br>const arr4 = Array(); // []<br>const arr5 = new Array(); // []<br><br>// 透過建構式可直接設定陣列當中的長度<br>const arr6 = Array(5); // 輸入單一數字時會建立多筆空值的陣列 [ , , , , ]<br>const arr7 = Array(1, 2, 3); //當輸入的資料多筆時視為多筆資料，這時候陣列中 [1,2,3]</pre><p>提取陣列內容時，只要在變數後使用中括號並加上索引就能取得相對資料</p><pre>arr3[0]; // &#39;A&#39;</pre><p>陣列當中唯一的屬性只有 length，透過 length 可得知陣列中有幾筆長度。但這時候要注意的是，因為陣列中可存放各種型別資料，也包含空值、null, undefined等多個特殊基本型別，如上個範例中的 arr6，建立了五個空資料，這時候 arr6.length 依然會回傳 5。</p><pre>arr1.length; // 0<br>arr2.length; // 1<br>arr3.length; // 3<br>arr4.length; // 0<br>arr5.length; // 0<br>arr6.length; // 5<br>arr7.length; // 3</pre><p>length 除了取得資料長度之外，最常使用於取得陣列最後一筆資料。此時要注意的是索引從 0 開始計算，因此取得最後一筆資料的方式</p><pre>arr3[arr3.length - 1]; // &#39;C&#39;</pre><h3>陣列可使用的方法</h3><p>陣列可使用的方法相當多，我個人分成幾類：資料修改、遍歷、排序、其它。</p><h4>資料修改</h4><p>主要是對陣列的新增、刪除。</p><p>unshift(element1, element2…)<br>將一個或多個元素放入陣列的開頭，放入後會更新原有資料。</p><pre>let arr = [4,5,6];<br>arr.unshift(3); // [3,4,5,6]<br>arr.unshift(1, 2); //[1,2,3,4,5,6]</pre><p><strong>shift()</strong><br>移除（取出）陣列中第一個元素，並返回被移除的元素，陣列也會跟著更新。</p><pre>let arr1 = [1,2,3,4,5,6];<br>arr1.shift(); // 會回傳 1，同時 arr 會變成 [2,3,4,5,6]<br><br>let arr2 = [1,2,3,4,5,6];<br>let getFirstEle = arr2.shift(); // 1<br>// 此時 arr2 會變成 [2,3,4,5, 6]，同時被移除的最後一個元素會存放至 getFirstEle 當中</pre><p><strong>push(element1, element2…)</strong><br>將一個或多個元素放入陣列的最後，放入後會更新原有資料。</p><pre>let arr = [1,2,3,4,5,6];<br>arr.push(7); // [1,2,3,4,5,6,7]<br>arr.push(8,9); //[1,2,3,4,5,6,7,8,9]</pre><p><strong>pop()</strong><br>移除（取出）陣列中最後一個元素，並返回被移除的元素，陣列也會跟著更新。</p><pre>let arr1 = [1,2,3,4,5,6];<br>arr1.pop(); // 會回傳 6，同時 arr 會變成 [1,2,3,4,5]<br><br>let arr2 = [1,2,3,4,5,6];<br>let getLastEle = arr2.pop(); // 6<br>// 此時 arr2 會變成 [1,2,3,4,5]，同時被移除的最後一個元素會存放至 getLastEle 當中</pre><p><strong>concat(arr1, arr2, …)</strong><br>合併兩個或多個陣列，合併後會返回一組新陣列，並不會改變原有的陣列。</p><pre>let arr1 = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];<br>let arr2 = [&#39;d&#39;, &#39;e&#39;, &#39;f&#39;];<br>let arr3 = [&#39;g&#39;, &#39;h&#39;];<br><br>let arr4 = arr1.concat(arr2, arr3);<br>// 最後合併後的 arr4 會變成 [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;]<br>// arr1, arr2, arr3 都不會被改變</pre><h4>遍歷</h4><p>去搜尋陣列中的資料，可根據有條件的回傳元素、索引或布林值。遍歷中的方法基本上都會有兩個參數，第一個為 CallBack 函式（callbackFn），第二個為指定執行函式時的 this 對象（thisArg），這個選項為非必要選項，可忽略。若 CallBack 函式使用箭頭函式，因為箭頭函式 this 的特性，thisArg 將無法生效。</p><p>遍歷之中 CallBack 函式的參數都是 item, index 與 array</p><ul><li>item: 迴圈執行時正在處理的當前元素</li><li>index: 當前元素的索引</li><li>array: 正在操作的陣列</li></ul><p><strong>forEach(callbackFn(item, index, array), thisArg)</strong><br>不會回傳任何東西，單純跑回圈將陣列裡所有元素執行過一次。</p><pre>let arr1 = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;];<br>let obj = {<br>  say: &#39;Hello&#39;<br>};<br><br>arr1.forEach(function(item, index, array) {<br>  console.log(item, index, array)<br>});<br>/*<br>a 0 (8) [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;]<br>b 1 (8) [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;]<br>c 2 (8) [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;]<br>d 3 (8) [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;]<br>e 4 (8) [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;]<br>f 5 (8) [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;]<br>g 6 (8) [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;]<br>h 7 (8) [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;]<br>*/<br><br>// callbackFn 也可使用 ES6 當中的箭頭函式寫法<br>arr1.forEach((item, index, array)=&gt;{<br>  console.log(item, index, array)<br>});<br><br>// thisArg<br>arr1.forEach(function(item, index, array) {<br>  console.log(this)<br>}, obj);<br>/*<br>{say: &#39;Hello&#39;}<br>{say: &#39;Hello&#39;}<br>...<br>*/</pre><p><strong>filter(callbackFn(item, index, array), thisArg)<br></strong>會依據設定的條件將符合的元素傳出，回傳一組符合條件的新陣列。而原有的陣列則不會被更動。下方案例為從 arr 陣列當中取得偶數，只要除以 2 餘數為 0 則符合條件。</p><pre>let arr = [1,2,3,4,5,6];<br><br>// 取出所有偶數<br>let arrEven = arr.filter((item)=&gt;item%2 === 0); // [2,4,6]<br>// 但此時原有的 arr 依然是 [1,2,3,4,5,6]</pre><p><strong>map(callbackFn(item, index, array), thisArg)</strong><br>會創立一組新陣列，並且每一個元素都會被遍歷一次。與 forEach 一樣，差別在於 forEach 遍歷原陣列但不會回傳任何東西，而 map 則是建立一個新的陣列並且遍歷後回傳。</p><pre>let arr = [1,2,3,4];<br><br>// 取出所有偶數<br>let newArr = arr.map((item) =&gt; item * 2); // [2, 4, 6, 8]<br>// 但此時原有的 arr 依然是 [1,2,3,4,5,6]</pre><p><strong>every(callbackFn(item, index, array), thisArg)</strong><br>測試陣列中每一個元素是否符合條件，全部符合才會回傳 true，否則為 false</p><pre>let arr1 = [1,2,3,4];<br>let arr2 = [2,4,6];<br><br>// 檢查是否全是偶數<br>let res1 = arr1.every(item =&gt; item % 2 === 0); // false<br>let res2 = arr2.every(item =&gt; item % 2 === 0); // true</pre><p>some(<strong>callbackFn(item, index, array), thisArg</strong>)<br>與 every 相似，但只要陣列中其中一個元素符合條件即為 true，若全部元素都不符合則回傳 false。</p><pre>let arr1 = [1,2,3,4];<br>let arr2 = [1,3,5];<br><br>// 檢查是否全是偶數<br>let res1 = arr1.some(item =&gt; item % 2 === 0); // true<br>let res2 = arr2.some(item =&gt; item % 2 === 0); // false</pre><p><strong>find(callbackFn(item, index, array), thisArg)</strong><br>將陣列中的元素帶入函式內做判斷，並且只回傳第一個符合條件的元素。若全部元素都不符合條件則回傳 undefind。</p><pre>let arr = [5, 12, 8, 130, 44];<br>let found = arr.find(item =&gt; item &gt; 10); // 回傳第一個大於 10 的元素，12</pre><p><strong>findIndex(callbackFn(item, index, array), thisArg)</strong><br>與 find 相似，差別在於回傳的是第一個條件相符的元素索引。若沒有符合條件則回傳 -1。</p><pre>let arr = [5, 12, 8, 130, 44];<br>let found = arr.findIndex(item =&gt; item &gt; 13);<br>// 回傳第一個大於 13 的元素索引，130 符合條件，因此回傳 130 的索引：3</pre><p><strong>findLast(callbackFn(item, index, array), thisArg)</strong><br>與 find 相似，但回傳的是滿足條件的最後一個元素。若沒有滿足條件則回傳 undefind。</p><pre>let arr = [5, 12, 8, 130, 44];<br>let found = arr.findLast(item =&gt; item &gt; 45); // 回傳最後一個大於 45 的元素，130</pre><p><strong>findLastIndex(callbackFn(item, index, array), thisArg)</strong><br>與 findIndex 相似，但回傳的是滿足條件的最後一個元素索引。若沒有滿足條件則回傳 -1。</p><pre>let arr = [5, 12, 8, 130, 44];<br>let found = arr.findLastIndex(item =&gt; item &gt; 45);<br>// 回傳最後一個大於 45 的元素，130 的索引為 3</pre><p><strong>reduce(callback(previousValue, currentValue, currentIndex, array), initiaValue)<br></strong>reduce 與其它遍歷稍微不同，CallBack 函數參數中多了一個 previousValue，呼叫上一次遍歷中的元素，若第一次執行則是陣列中第一個元素。reduce 沒有 thisArg，但可用 initaValue 來指定第一次執行遍歷時的 previousValue 初始值。</p><pre>let arr1 = [1, 2, 3, 4];<br>let sum1 = arr1.reduce(<br>  (previousValue, currentValue) =&gt; previousValue + currentValue,<br>  0 // initiaValue 為 0，此時第一次調用時 previousValue 則為 0<br>); // 10<br><br>let sum2 = arr1.reduce(<br>  (previousValue, currentValue) =&gt; previousValue + currentValue,<br>  100 // initiaValue 為 100，此時第一次調用時 previousValue 則為 100<br>); // 110<br></pre><p><strong>reduceRight(callback(previousValue, currentValue, currentIndex, array), initiaValue)<br></strong>與 reduce 相同，只是從右至左。加法時沒有差別，但對於減法來說會有不同的結果。</p><pre>let arr1 = [1, 2, 3, 4];<br>let res1 = arr1.reduce(<br>  (previousValue, currentValue) =&gt; previousValue - currentValue<br>); // -8<br><br>let res2 = arr1.reduceRight(<br>  (previousValue, currentValue) =&gt; previousValue - currentValue<br>); // -2</pre><h4>排序</h4><p><strong>sort(compareFn(a, b))</strong></p><p>陣列中的排序若沒有執行比對函式，則會先被轉成字串，根據 unicode 順序回傳排序結果。因此數字排列就會發生 1, 10, 2, 3 這種非預期的結果。使用 sort 之後的陣列將會更改原陣列資料。</p><pre>const months = [&#39;March&#39;, &#39;Jan&#39;, &#39;Feb&#39;, &#39;Dec&#39;];<br>months.sort(); // [&quot;Dec&quot;, &quot;Feb&quot;, &quot;Jan&quot;, &quot;March&quot;]<br><br>const nums = [1, 30, 4, 21, 100000];<br>nums.sort(); // [1, 100000, 21, 30, 4]</pre><p>透過 compareFn 裡的 a 與 b 參數做比對，可決定排序的順序</p><pre>const nums = [1, 30, 4, 21, 100000];<br>nums.sort((a, b) =&gt; {<br>  if (a &gt; b) return 1;<br>  if (a &lt; b) return -1;<br>  return 0;<br>}); // [1, 4, 21, 30, 100000]</pre><p><strong>reserve()<br></strong>單純將陣列順序反轉，反轉後原陣列資料將被改變。</p><pre>const arr = [&#39;one&#39;, &#39;two&#39;, &#39;three&#39;];<br>arr.reverse(); //[&quot;three&quot;, &quot;two&quot;, &quot;one&quot;]</pre><h4>分割</h4><p>slice(start, end)<br>取得 start 與 end 兩個索引位置之間的元素，並回傳新的陣列。原陣列並不會被改變。</p><ul><li>start: 提取起始的索引位置，非必填。若沒有設置起始位置，則不會有任何動作。若為負整數，則從陣列最後開始提取。</li><li>end: 提取終止的索引位置，非必填。若沒有設置終止位置，則會取得起始位置之後的所有元素。</li></ul><pre>const animals = [&#39;ant&#39;, &#39;bison&#39;, &#39;camel&#39;, &#39;duck&#39;, &#39;elephant&#39;];<br>animals.slice(2) // [&quot;camel&quot;, &quot;duck&quot;, &quot;elephant&quot;]<br>animals.slice(2, 4) // [&quot;camel&quot;, &quot;duck&quot;]<br>animals.slice(1, 5) // [&quot;bison&quot;, &quot;camel&quot;, &quot;duck&quot;, &quot;elephant&quot;]<br>animals.slice(-2) // [&quot;duck&quot;, &quot;elephant&quot;]<br>animals.slice(2, -1) // [&quot;camel&quot;, &quot;duck&quot;]<br>animals.slice() // [&quot;ant&quot;, &quot;bison&quot;, &quot;camel&quot;, &quot;duck&quot;, &quot;elephant&quot;]</pre><p><strong>splice(start, deleteCount, item1, item2, itemN)</strong><br>可刪除、替換、原地添加新元素來修改陣列內容。</p><pre>const months = [&#39;Jan&#39;, &#39;March&#39;, &#39;April&#39;, &#39;June&#39;];<br>months.splice(1, 0, &#39;Feb&#39;); //[&quot;Jan&quot;, &quot;Feb&quot;, &quot;March&quot;, &quot;April&quot;, &quot;June&quot;]<br>months.splice(4, 1, &#39;May&#39;); //[&quot;Jan&quot;, &quot;Feb&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;]</pre><p>copyWithin(target, start, end)<br>複製陣列中一部分元素到同個陣列中的另一個位置。陣列內容會被改變，但長度不會改變。</p><pre>const arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;];<br>arr.copyWithin(0, 3, 4); // [&quot;d&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;]<br>arr.copyWithin(1, 3); // [&quot;d&quot;, &quot;d&quot;, &quot;e&quot;, &quot;d&quot;, &quot;e&quot;]</pre><h4>其它</h4><p><strong>at(index)</strong><br>取得指定索引位置的元素，允許正負整數。若是負整數則從陣列最後一個元素倒數計算。</p><pre>const arr = [5, 12, 8, 130, 44];<br>arr.at(2); //8<br>arr.at(-2); //130<br><br>// 通常可在陣列後使用中括號直接輸入索引取得<br>arr[2]; // 8，但這個方法無法使用負整數</pre><p><strong>fill(value, start, end)</strong><br>將一個固定值填滿陣列中指定的元素範圍。</p><pre>const arr = [1, 2, 3, 4];<br>arr.fill(0, 2, 4); // [1, 2, 0, 0]<br>arr.fill(5, 1); // [1, 5, 5, 5]<br>arr.fill(6); // [6, 6, 6, 6]</pre><p>flat(depth) <br>一個陣列之中可能有一個或多個子陣列元素，flat 可用於合併這些陣列，並且設定資料深度。depth 預設為 1，若是要合併任意深度可使用 Infinity。</p><pre>var arr1 = [1, 2, [3, 4]];<br>arr1.flat(); // [1, 2, 3, 4];<br><br>var arr2 = [1, 2, [3, 4, [5, 6]]];<br>arr2.flat(); // [1, 2, 3, 4, [5, 6]]<br><br>var arr3 = [1, 2, [3, 4, [5, 6]]];<br>arr3.flat(2); // [1, 2, 3, 4, 5, 6]<br><br>//使用 Infinity，可展开任意深度的嵌套数组<br>var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];<br>arr4.flat(Infinity);<br>// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</pre><p><strong>flatMap(callbackFn(item, index, arrau), thisArg)</strong><br>使用方式與 flat 深度為 1 時相似，但 flatMap 會遍歷每一個元素，然後壓縮成一個新的陣列。</p><pre>const arr1 = [1, 2, [3], [4, 5], 6, []];<br>const flattened = arr1.flatMap(num =&gt; num);<br>// [1, 2, 3, 4, 5, 6]</pre><p><strong>from(arrayLike, mapFn(item, index), thisArg)</strong><br>可將含有 length 或有索引屬性的任意對象轉換成陣列，包含字串、Map, Set 等多種型別。同時轉換陣列後可使用 mapFn 執行 map 返回結果。這一連串行為相當於 Array.from(obj).map()。mapFn 與 thisArg 為可選項目。</p><pre>Array.from(&#39;foo&#39;);<br>// [ &quot;f&quot;, &quot;o&quot;, &quot;o&quot; ]<br><br>const set = new Set([&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;, &#39;foo&#39;]);<br>Array.from(set);<br>// [ &quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot; ] <br>// 因為 Set 只會存放不重複資料，因此最後一個 foo 不會被存入 set 當中<br><br>const map = new Map([[1, 2], [2, 4], [4, 8]]);<br>Array.from(map);<br>// [[1, 2], [2, 4], [4, 8]]<br><br>const mapper = new Map([[&#39;1&#39;, &#39;a&#39;], [&#39;2&#39;, &#39;b&#39;]]);<br>Array.from(mapper.values());<br>// [&#39;a&#39;, &#39;b&#39;];<br><br>Array.from(mapper.keys());<br>// [&#39;1&#39;, &#39;2&#39;];</pre><p><strong>includes(searchElement, fromIndex)</strong><br>判斷陣列中是否包含指定的值，如果包含回傳 true，否則為 false。</p><p>fromIndex 可以指定從索引位置開始尋找，是非必要選項。fromIndex 必須為整數，若為負數則是 array.length + fromIndex 開始尋找，不會反方向搜尋。預設為 0。</p><pre>[1, 2, 3].includes(2);     // true<br>[1, 2, 3].includes(4);     // false<br>[1, 2, 3].includes(3, 3);  // false<br>[1, 2, 3].includes(3, -1); // true<br>[1, 2, NaN].includes(NaN); // true</pre><p><strong>indexOf(searchElement, fromIndex)</strong><br>搜尋指定元素的第一個索引。如不存在則回傳 -1。</p><p>fromIndex 為選填項目，預設為 0。若指定索引大於陣列長度，則回傳 -1。若指定負整數則倒數第二個開始尋找到最後一個元素，但尋找方向不會改變。</p><pre>const array = [2, 9, 9];<br>array.indexOf(2);     // 0<br>array.indexOf(7);     // -1<br>array.indexOf(9, 2);  // 2<br>array.indexOf(2, -1); // -1<br>array.indexOf(2, -3); // 0</pre><p><strong>lastIndexOf(searchElement, fromIndex)</strong><br>與 indexOf 相同，但從最後一個索引開始往前尋找。這裡的 fomeIndex 預設值為 array.length — 1。</p><pre>var array = [2, 5, 9, 2];<br>var index = array.lastIndexOf(2);<br>// index is 3<br>index = array.lastIndexOf(7);<br>// index is -1<br>index = array.lastIndexOf(2, 3);<br>// index is 3<br>index = array.lastIndexOf(2, 2);<br>// index is 0<br>index = array.lastIndexOf(2, -2);<br>// index is 0<br>index = array.lastIndexOf(2, -1);<br>// index is 3</pre><p><strong>isArray</strong><br>檢查值是否為陣列</p><pre>Array.isArray([1, 2, 3]);  // true<br>Array.isArray({foo: 123}); // false<br>Array.isArray(&#39;foobar&#39;);   // false<br>Array.isArray(undefined);  // false</pre><p><strong>join(separator)</strong><br>將陣列轉換成一組字串。可透過 separator 參數指定各元素之間的分隔字符，如果沒有設置則預設為 , 相隔。若陣列只有一個元素，則不會出現分隔字符。</p><pre>const elements = [&#39;Fire&#39;, &#39;Air&#39;, &#39;Water&#39;];<br>elements.join() // &quot;Fire,Air,Water&quot;<br>elements.join(&#39;&#39;) // &quot;FireAirWater&quot;<br>elements.join(&#39;-&#39;) // &quot;Fire-Air-Water&quot;</pre><p><strong>toLocaleString(locales, options)</strong><br>將陣列中的資料本地化，可用於物件、數字與日期資料。常用於幣別、日期轉換。locale 可設置國碼，options 可以物件資料設定多個條件。</p><pre>// 日幣<br>let prices = [&#39;300&#39;, 500, 8236, 42];<br>prices.toLocaleString(&#39;ja-JP&#39;,{style:&#39;currency&#39;,currency: &#39;JPY&#39;}); <br>// &quot;300,￥500,￥8,236,￥42&quot;<br><br>// 新台幣<br>let prices = [300, 500, 8236, 42];<br>prices.toLocaleString(&#39;zh-TW&#39;,{style:&#39;currency&#39;,currency: &#39;TWD&#39;});<br>// &quot;$300.00,$500.00,$8,236.00,$42.00&quot;<br><br>// 法國歐元<br>let prices = [&#39;300&#39;, 500, 8236, 42];<br>prices.toLocaleString(&#39;fr-FR&#39;,{style:&#39;currency&#39;,currency: &#39;EUR&#39;});<br>&quot;300, 500,00 €, 8 236,00 €, 42,00 €&quot; // 因為&#39;300&#39;是字串，所以會忽略。<br><br>// 沒給參數 人在台灣所以是台灣時間格式<br>let date = new Date();<br>const arr = [&#39;Taiwan, Tainan&#39;, date ];<br>arr.toLocaleString(); <br>// &quot;Taiwan, Tainan,2019/10/11 上午4:38:08&quot;<br><br>// 日本時間<br>let dateJp = new Date();<br>const arrJp = [&#39;Japan, Osaka&#39;, dateTw];<br>arrJp.toLocaleString(&#39;ja-JP&#39;); <br>// &quot;Japan, Osaka,2019/10/11 4:38:40&quot;</pre><p><strong>toString()</strong><br>將陣列轉換成字串。</p><pre>const arr = [1, 2, &#39;a&#39;, &#39;1a&#39;];<br>arr.toString(); // &quot;1,2,a,1a&quot;</pre><p><strong>of(element1, element2…)</strong><br>透過這個方法創建新的 Array 實例。</p><pre>Array.of(1);         // [1]<br>Array.of(1, 2, 3);   // [1, 2, 3]<br>Array.of(undefined); // [undefined]</pre><h4>Array Iterator</h4><p>Iterator 中文大多稱為迭代器。每一個迭代器裡面具有 next() 方法，會回傳下一筆迭代器資料。每一筆迭代資料會有 value 與 done。</p><ul><li>value: 存放原陣列元素，包含索引與資料。如果已經跳脫最後一筆資料則顯示 undefined。</li><li>done: 則是紀錄是否還有下一筆資料，如果還有下一筆顯示 false，如果已經跳脫最後一筆則為 true</li></ul><p>Interator 的概念比較類似 Linked List。會有一個儲存資料與下一筆關聯的對象。</p><p><strong>entries()</strong><br>回傳一組新的迭代資料，每一筆資料包含索引與元素。</p><pre>const array1 = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];<br>const iterator1 = array1.entries();<br><br>console.log(iterator1.next());<br>// done: false, value: [0, &#39;a&#39;]<br>console.log(iterator1.next());<br>// done: false, value: [1, &#39;B&#39;]<br>console.log(iterator1.next());<br>// done: false, value: [2, &#39;C&#39;]<br>console.log(iterator1.next());<br>// done: true, value: undefined</pre><p><strong>keys</strong><br>回傳陣列中每一個索引，會以 Array Iterator 格式呈現。</p><pre>const array1 = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];<br>const iterator = array1.keys();<br><br>for (const key of iterator) {<br>  console.log(key);<br>}<br><br>// Expected output: 0<br>// Expected output: 1<br>// Expected output: 2</pre><p><strong>values</strong><br>回傳陣列中每一個元素，並以 Array Iterator 格式呈現。</p><pre>const array1 = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];<br>const iterator = array1.values();<br><br>for (const value of iterator) {<br>  console.log(value);<br>}<br><br>// Expected output: &quot;a&quot;<br>// Expected output: &quot;b&quot;<br>// Expected output: &quot;c&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5abb68ae337" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>