简体   繁体   中英

What is the purpose of a statement in square brackets after an array push call?

I've been working at a problem on FreeCodeCamp called "9 billion names of God the integer" . (The specifics of the problem itself aren't germane to my question, but have a look at the link if you're interested.) Admittedly I wrestled with this problem for several days before giving up and googling the answer. The problem originally comes from Rosetta Code, and I set about reading the answer provided for JavaScript to make sure I understood how this problem could be solved.

As far as I can tell, it's making calculations via good old-fashioned for loops, and even though it was published with short, non-descriptive variable names, I think I could work my way through it. However, here is the part that's tripping me up (note that the code below is a cleaned-up reproduction of the Rosetta Code solution, which had a lot of unnecessary comments and a couple of typos):

(function() {
  var cache = [
    [1]
  ];

  function cumu(n) {
    var r, l, x, Aa, Mi;
    for (l = cache.length; l < n + 1; l++) {
      r = [0];
      for (x = 1; x < l + 1; x++) {
        r.push(r[r.length - 1] + (Aa = cache[l - x < 0 ? cache.length - (l - x) : l - x])[(Mi = Math.min(x, l - x)) < 0 ? Aa.length - Mi : Mi]);
      }
      cache.push(r);
    }
    return cache[n];
  }

  function row(n) {
    var r = cumu(n),
      leArray = [],
      i;
    for (i = 0; i < n; i++) {
      leArray.push(r[i + 1] - r[i]);
    }
    return leArray;
  }

  console.log("Rows:");
  for (iterator = 1; iterator < 12; iterator++) {
    console.log(row(iterator));
  }

  console.log("Sums");
  [23, 123, 1234].forEach(function(a) {
    var s = cumu(a);
    console.log(a, s[s.length - 1]);
  });
})()

Specifically this line within cumu(n) :

r.push(r[r.length - 1] + (Aa = cache[l - x < 0 ? cache.length - (l - x) : l - x])[(Mi = Math.min(x, l - x)) < 0 ? Aa.length - Mi : Mi]);

This push method has [square brackets] after it. What does that do? I know the purpose of brackets as they pertain to arrays and objects, but I can't find any documentation about this usage. Mind you, the script seems to work as intended regardless, with the result printing to the console as expected and no errors coming up.

(Aa = cache[l - x < 0 ? cache.length - (l - x) : l - x]) 

returns an array as cache is a multidimensional array. It is between the parentheses because Aa needs to be set as well.

The great problem of this code is that it is hard to read. It could be wise to open up your IDE and restructure the code piece by piece. Then you will be able to better understand it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM