I cannot understand a behavior of this JS code. The d
object in this loop becomes somehow nested in a browser console. Run the code snippet below in a browser or see it in http://jsfiddle.net/qhsjyzob/ and check the second and third console.log
in the browser console. Why does it show that the d
object is like this:
{
Hello: {
World: {}
}
}
when it has to be like this only:
{
Hello: {}
}
Here is the code or in http://jsfiddle.net/qhsjyzob/:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
'use strict';
var e = ['Hello', 'World'];
var d = {}
for (var g = 0; g < e.length; g++) {
console.log("1: ", d, g, d[e[g]], e[g]);
d[e[g]] = d[e[g]] || {};
console.log("2: ", d, g, d[e[g]], e[g]);
console.log("3: ", d, g, d[e[g]], e[g]);
d = d[e[g]]
console.log("4: ", d, g, d[e[g]], e[g]);
}
</script>
</body>
</html>