Each Method?

Milena

The woman of many questions
Veteran
Joined
Jan 26, 2014
Messages
1,282
Reaction score
106
First Language
Irish
Primarily Uses
N/A
members.each{|enemy| @wereforms << enemy.wereforms?}In this example above (in class Game_Troop) in RGSS3, we can extract the values of enemy and push the enemy into array wereforms if they are wereforms. Now, how can you do each method in JavaScript?
 

estriole

Veteran
Veteran
Joined
Jun 27, 2012
Messages
1,033
Reaction score
338
First Language
indonesian
another approach is using for... but don't use for (in)... but for (of)

Code:
// let's say you already grab the members above herefor (var enemy of members){   if(urmethodthatreturntruefalse)    wereforms.push(enemy);}
 
Last edited by a moderator:

Milena

The woman of many questions
Veteran
Joined
Jan 26, 2014
Messages
1,282
Reaction score
106
First Language
Irish
Primarily Uses
N/A
Evgenji and Estriole, thanks, you both solved two of my problems already :D
 

DarknessFalls

Rpg Maker Jesus - JS Dev.
Veteran
Joined
Jun 7, 2013
Messages
1,393
Reaction score
209
First Language
English
theres .forEach and .map, no one really usese for(i = 0 ...) any more, least not at work we don't. We use forEach if we need a loop
 

Tsukihime

Veteran
Veteran
Joined
Jun 30, 2012
Messages
8,230
Reaction score
3,075
First Language
English
theres .forEach and .map, no one really usese for(i = 0 ...) any more, least not at work we don't. We use forEach if we need a loop
I iterate over indices.


I could use the (for var of array), but I haven't use forEach.


forEach offers you its own scope, but you can't break out of the loop until it's finished


There are situations where I want to break out of a loop, and that's when I iterate it the old-fashion way.


I only use map if I'm performing an operation on a set of values.


I don't know what the performance impact of each loop method is.
 
Last edited by a moderator:

DarknessFalls

Rpg Maker Jesus - JS Dev.
Veteran
Joined
Jun 7, 2013
Messages
1,393
Reaction score
209
First Language
English
.map returns you an array, .forEach does not. Thats the biggest difference I know, with .map you get back an array of "changed" values which is really good for mutability.
 

Tsukihime

Veteran
Veteran
Joined
Jun 30, 2012
Messages
8,230
Reaction score
3,075
First Language
English
.map returns you an array, .forEach does not. Thats the biggest difference I know, with .map you get back an array of "changed" values which is really good for mutability.
What's the motivation to using .forEach over iterating over index, and the

for (var obj of elements) {}?I'm looking at this and it seems better to just go with the "old" ways of doing it

https://jsperf.com/for-vs-foreach/9
 
Last edited by a moderator:

DarknessFalls

Rpg Maker Jesus - JS Dev.
Veteran
Joined
Jun 7, 2013
Messages
1,393
Reaction score
209
First Language
English
When I use:

for (var obj in Object) { ... }I only use it when looping over objects.

When I use:

array.forEach(function(arrayElement) { ... });I want to walk over an array of elements, you cannot use forEach on an object.

Now forEach will just loop over. If I want to I can do:

var something = array.map(function() { ... });Now here I am able to loop over the array, make changes to the elements and get a whole new array back, leaving the original array in tact.

So to sum up:

for (var key in Object) {} // Only used on objectsarray.forEach(function(){}) // better then for (var i = 0; ...)array.map(function(){}) // Fabulous for making changes to elements in the array and not // mutating it.Questions? Comments? Death Threats? (LOL) 
 

Tsukihime

Veteran
Veteran
Joined
Jun 30, 2012
Messages
8,230
Reaction score
3,075
First Language
English
What do you mean by you can't use forEach on an object?

If I were to say

Code:
for (var obj in someObj) {}
Are there deterministic behaviors for non-array objects?
 

Amuseum

Veteran
Veteran
Joined
Oct 27, 2015
Messages
71
Reaction score
66
First Language
English Chinese
Primarily Uses
RMXP
What's the motivation to using .forEach over iterating over index, and the

for (var obj of elements) {}?I'm looking at this and it seems better to just go with the "old" ways of doing it

https://jsperf.com/for-vs-foreach/9
very interesting site. i made some more test cases : for..in and for..of

http://jsperf.com/for-vs-foreach/405

the most consistently fastest across all browsers is this version:

for loop, local vars

for (var i = 0, len = values.length; i < len; i++) {  add(values);}that is, localize all variables that will be used in the loop. 

foreach is sufficiently fast, but how it's coded also matter between browsers. 

straightforward "array.forEach(func);" is faster on Firefox and slower on Chrome, but only if func is a named function. anonymous function decreases performance.

for..in and for..of both have terrible performance. about 80% to 90% slower than regular loops.
 
Last edited by a moderator:

Tsukihime

Veteran
Veteran
Joined
Jun 30, 2012
Messages
8,230
Reaction score
3,075
First Language
English
It's...pretty strange that we have to cache the length ourselves.


I can see why some people do that in other languages like Java, and then are told that the java compilers tend to optimize that for you.


I'm surprised the javascript engine doesn't optimize that.


I'm assuming the reason why the cached one is slower than the reverse one is because it's caching the length on every test, rather than caching it once across all tests.
 
Last edited by a moderator:

Amuseum

Veteran
Veteran
Joined
Oct 27, 2015
Messages
71
Reaction score
66
First Language
English Chinese
Primarily Uses
RMXP
probably something about heaps and cache, which the CPU takes advantage of and depends on how the script engine is compiled and optimized. for Firefox, it doesn't seem to matter whether you localize the variables, all inline loops are equally fast. but for Chrome it definitely helps.

I made a new test case for a map function. it's the fastest method yet on Chrome -- almost twice as fast as inline loop. but on Firefox a bit slower than inline loop, but still excellent.

function map(array, func) {for (var i = 0, a = array, len = a.length, f = func; i < len; i++) { f(a);}}map(values, add);So that seems to be the best way to iterate for Chrome and Firefox.also added array.map and array.reduce, and both are really slow.
 
Last edited by a moderator:

Tsukihime

Veteran
Veteran
Joined
Jun 30, 2012
Messages
8,230
Reaction score
3,075
First Language
English
I made a new test case for a map function. it's the fastest method yet on Chrome -- almost twice as fast as inline loop. but on Firefox a bit slower than inline loop, but still excellent.

function map(array, func) {for (var i = 0, a = array, len = a.length, f = func; i < len; i++) { f(a);}}map(values, add);So that seems to be the best way to iterate for Chrome and Firefox.also added array.map and array.reduce, and both are really slow.

Wow, twice as fast! Amazing,

V8 engine might be one of the fastest engines, but if I can't write a simple indexed for loop without having to hand-optimizing it...

Well, premature optimization being evil and whatnot. I'll stick with

for (var i = 0; i < arr.length; i++) {}Even if I know it's not optimal.Hopefully there's a script processor that I can run through that will automatically take care of these things :)
 
Last edited by a moderator:

estriole

Veteran
Veteran
Joined
Jun 27, 2012
Messages
1,033
Reaction score
338
First Language
indonesian
Difference between for...of and for...in

The following example shows the difference between a for...of loop and a for...in loop. While for...in iterates over property names, for...of iterates over property values:

let arr = [3, 5, 7];arr.foo = "hello";for (let i in arr) {console.log(i); // logs "0", "1", "2", "foo"}for (let i of arr) {console.log(i); // logs "3", "5", "7"}Using Array.prototype.forEach()

To get the same property values the for...of loop would return, you can also use the Array.prototype.forEach() method:

let arr = [3, 5, 7];arr.foo = "hello";arr.forEach(function (element, index) {console.log(element); // logs "3", "5", "7"console.log(index); // logs "0", "1", "2"});// or with Object.keys()Object.keys(arr).forEach(function (element, index) {console.log(arr[element]); // logs "3", "5", "7", "hello"console.log(arr[index]); // logs "3", "5", "7", undefined});source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

additional note:

for of loop was introduced in ES6 which allows you to easily iterate over elements of an collection.for of iterates over the values of elements of a collection not the keys. A collection can be an array, set, list, custom collection object etc.

Earlier to ES6 we had to use for loop or Array’s foreach loop to walkthrough elements of an collection. ES6 introduced a new way for iteration.

so i guess it would be better using forEach?
 
Last edited by a moderator:

Amuseum

Veteran
Veteran
Joined
Oct 27, 2015
Messages
71
Reaction score
66
First Language
English Chinese
Primarily Uses
RMXP
Wow, twice as fast! Amazing,

V8 engine might be one of the fastest engines, but if I can't write a simple indexed for loop without having to hand-optimizing it...

Well, premature optimization being evil and whatnot. I'll stick with

for (var i = 0; i < arr.length; i++) {}Even if I know it's not optimal.Hopefully there's a script processor that I can run through that will automatically take care of these things :)
Chrome is optimized for closures and anonymous functions, which is why map() is so fast. this is to support the rising popularity of functional programming. however, it seems the standard array.map() and array.reduce() are poorly supported. so you should write your own map function.but regular loops are still sufficiently fast, as long as you localize the variables, including the array, like so:

Code:
for (var i = 0, a = array, len = a.length, f=func; i < len; i++) {  f(a[i]);}
i discovered something even more amazing. someone else suggested using pop:
Code:
for (var i; i = values.pop(); ) sum += i
This runs infinitely faster. no joke. the test result literally said "Infinity" in Firefox. In chrome it was 60,000 times faster than map(). either there's something wrong with the test or something crazy going on with pop(). caveat is pop removes all elements from the array, so make sure you copy the array beforehand if you still need it (don't use array.slice()):

Code:
var b = [];for (var i = 0, a = values, l = a.length; i < l; i++) {  b[i] = a[i];}for (var i; i = b.pop(); ) sum += i
See for yourself: http://jsperf.com/for-vs-foreach/407
 
Last edited by a moderator:

DarknessFalls

Rpg Maker Jesus - JS Dev.
Veteran
Joined
Jun 7, 2013
Messages
1,393
Reaction score
209
First Language
English
What do you mean by you can't use forEach on an object?If I were to say

for (var obj in someObj) {}Are there deterministic behaviors for non-array objects?
How is that .forEach?
 

estriole

Veteran
Veteran
Joined
Jun 27, 2012
Messages
1,033
Reaction score
338
First Language
indonesian
javascript array is more confusing than ruby :D . i need to do few console.log test before i'm sure it throw what i wanted...

and i also just experience some silly things happening... i strugle in hash + finding matching element using regexp for about 3 hours...

it's for grabbing the plugin parameters. filter it by regexp. and only add parameter that have certain regexp pattern and value not null ("")..

it's supposed to be simple...

i'm sure the code is right... changing it few times using variation of forEach, for(...in), for(...of), regular for...

i also sure my regexp is correct. but it always throw empty... (data not match)...

you know what's wrong...??? it apparently... I need to reopen my plugin editor... double click... then press ok... to refresh the changes

i made to plugin parameter... i feel so stupid >.<.

just wanna share this... in case someone have same experience... if you're changing your plugin parameters from js files... (any change)

REOPEN your plugin editor... RECLICK on your plugin T.T. so you don't waste 3 hour like me.
 
Last edited by a moderator:

Iavra

Veteran
Veteran
Joined
Apr 9, 2015
Messages
1,797
Reaction score
859
First Language
German
Primarily Uses
Yeah, when you add a plugin to the list, it updates the plugin.js file, which includes the plugin name, description and parameters. If you change one of these, you'll need to refresh the plugin.
 

DarknessFalls

Rpg Maker Jesus - JS Dev.
Veteran
Joined
Jun 7, 2013
Messages
1,393
Reaction score
209
First Language
English
javascript array is more confusing than ruby :D . i need to do few console.log test before i'm sure it throw what i wanted...

and i also just experience some silly things happening... i strugle in hash + finding matching element using regexp for about 3 hours...

it's for grabbing the plugin parameters. filter it by regexp. and only add parameter that have certain regexp pattern and value not null ("")..

it's supposed to be simple...

i'm sure the code is right... changing it few times using variation of forEach, for(...in), for(...of), regular for...

i also sure my regexp is correct. but it always throw empty... (data not match)...

you know what's wrong...??? it apparently... I need to reopen my plugin editor... double click... then press ok... to refresh the changes

i made to plugin parameter... i feel so stupid >.<.

just wanna share this... in case someone have same experience... if you're changing your plugin parameters from js files... (any change)

REOPEN your plugin editor... RECLICK on your plugin T.T. so you don't waste 3 hour like me.
the only thing I need to do when I change a a script is copy it over, command+r in the console while the games running, boom done.
 

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Profile Posts

My first Video Scene - Kraken Art By @whtdragon -

Still needs work but its a start.
Considering a side project of making a Choose Your Own Adventure in MV but letting people play it as YouTube videos with the choices at the end leading to other videos. Thoughts?
I've made a rudimentary prototype map for the first game with the MV RTP overworld tiling. I'm probably going to photoshop the crap out of it for parallax, but the prototype has given me new ideas about how I want to place dungeons in the game.
I got tired of not having an avatar image. Couldn't think of anything cool. So I'm just using my game's antagonist instead... How original. At least both of our names start with C?
Expectation: Design/dev a game for the game jam | Reality: "These codes suck, why did I do it this way? lemme fix this. Also what if I add feature xyz because... well, I can."

Forum statistics

Threads
95,635
Messages
930,612
Members
125,950
Latest member
Tocilux
Top