<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Empty Array on Rowanto Luo</title><link>https://log.rowanto.com/categories/empty-array/</link><description>Recent content in Empty Array on Rowanto Luo</description><generator>Hugo -- gohugo.io</generator><language>en</language><lastBuildDate>Thu, 09 Feb 2017 19:39:51 +0000</lastBuildDate><atom:link href="https://log.rowanto.com/categories/empty-array/index.xml" rel="self" type="application/rss+xml"/><item><title>JavaScript, filling an array with empty array.</title><link>https://log.rowanto.com/posts/javascript-filling-an-array-with-empty-array/</link><pubDate>Thu, 09 Feb 2017 19:39:51 +0000</pubDate><guid>https://log.rowanto.com/posts/javascript-filling-an-array-with-empty-array/</guid><description>
&lt;p&gt;I love JavaScript, however very often, it doesn&amp;rsquo;t love me back.&lt;/p&gt;
&lt;pre tabindex="0"&gt;&lt;code&gt;const dataBuffers = new Array(4);
dataBuffers.fill([]);
for (let i = 0; i &amp;lt; 4; i += 1) {
dataBuffers[i].push(7);
}
console.log(JSON.stringify(dataBuffers));
// guess what is the answer?
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If you guess the answer would be &lt;code&gt;[[7],[7],[7],[7]]&lt;/code&gt;, then think again.&lt;/p&gt;
&lt;p&gt;The problem is that &lt;code&gt;dataBuffers.fill([])&lt;/code&gt; will create you a single array, and fills the dataBuffers with the reference of the array. It is actually pretty clear if you have done JavaScript or any language long enough, but one might be stuck with the impression that the dataBuffers is filled with an empty array. In actuality, they all reference to the single same array, which means, the result of the above is.&lt;/p&gt;</description></item></channel></rss>