Pal Pal - 3 months ago 9
Javascript Question

When pushing an array into another one, how to prevent flattening?

I would expect this:

var x = [1,2];
var y = [3,4];
x.push(y);
x


to yield this:

[1,2,[3,4]]


But some implementations (1) yield this:

[1,2,3,4]


Why? And how can I get the first result?


  1. InDesign 8.1 ExtendScript; some
    '/usr/bin/js'
    on OSX 10.10.5 that I can’t identify (doesn’t respond to
    man
    ,
    version()
    or
    --version
    ).


Nau Nau
Answer

if you run this code, you get the first result([1,2,[3,4]]), but if you print this in html, you see as the second result. You can try to see it in console.log In this JSFiddle you can try it: https://jsfiddle.net/gjLdb4rq/1/ (see the console log)

  var x = [1,2];
  var y = [3,4];
  x.push(y);
  console.log(x); //here prints in the console the [1,2,[3,4]]
  document.getElementById('result').innerHTML=x; //here prints in the html the [1,2,3,4]