JavaScript for game designer: Getting Loopy with Arrays

One of the things you do most often as a game designer is loop through arrays. Does the following code look familiar?

let planets = ["jupiter", "venus", "saturn", "mars"];
for (let i = 0; i < planets.length; i++) {
  planet = planets[i];
  console.log(planet);
}

It displays the name of each planet in the console:

jupiter
venus
saturn
mars

This is a classic bit of code, which gets a nice update with ES6. Because the i loop index counter is defined using let, it is local to the for loop. That means you can reuse the variable name i in as many other loops as you like, and their values won’t conflict.

Our dear old for loop still has its place in JavaScript, and often it’s still the best tool for the job. But with JavaScript ES6 (and ES5) you have some convenient new methods for looping through arrays that can help make your code a lot more readable.

 Note  for loops tend to be highly optimized by JavaScript engines like V8 and SpiderMonkey, and so they are still the safest bet for games where you may be looping through thousands of objects each frame. In this book I’ll highlight when it’s generally safe to use one of the newer loop methods, and when you should probably play it safe with a for loop. If you’re curious about the relative performance differences between different loop methods on the platform you’re using, visit jsperf.com and run a few test cases.

Вас заинтересует / Intresting for you:

Why is JavaScript a Good Choic...
Why is JavaScript a Good Choic... 587 views Денис Thu, 20 Sep 2018, 15:50:46
JavaScript for game designer: ...
JavaScript for game designer: ... 170 views Antoni Tue, 27 Nov 2018, 14:28:10
What is RESTful? Full descript...
What is RESTful? Full descript... 216 views Zero Cool Wed, 31 Oct 2018, 09:40:56
jQuery Fundamentals for APEX P...
jQuery Fundamentals for APEX P... 1852 views Гвен Sun, 03 Jun 2018, 13:07:04

Comments on JavaScript for game designer: Getting Loopy with Arrays

Be the first to comment
Please login to comment