JavaScript for game designer: Getting Loopy with Arrays

Антон Меринов

Антон Меринов

Автор статьи. Интересы, навыки: Профессиональное администрирование СУБД Oracle Database, веб-разработка, IT-World. Подробнее.

 
 
 

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... 1547 views Денис Thu, 20 Sep 2018, 15:50:46
JavaScript for game designer: ...
JavaScript for game designer: ... 1254 views Antoni Tue, 27 Nov 2018, 14:28:10
Working with a database in Wor...
Working with a database in Wor... 3853 views Андрей Васенин Tue, 16 Nov 2021, 16:23:40
How to uese WordPress multisit...
How to uese WordPress multisit... 2054 views Гвен Sun, 20 Mar 2022, 07:01:34
Comments (0)
There are no comments posted here yet
Leave your comments
Posting as Guest
×
Suggested Locations