ForEach inside an object

I have a question regarding this piece of code.

var names = ["John", "Jen", "Tony"]; var obj = { prob: function () { for (var i = 0; i < names.length; i++) { document.write(names[i]); console.log(names[i]); } }, trim: names.forEach(function(name) { document.write(name) console.log(name) }) } console.log("*********") console.log(obj.prob()); console.log("*********") 

If I run this code in the console, I will get the following:

 John Jen Tony ********* John Jen Tony undefined ********* 

This means that before my trial function, I run the trim function. Why is this? I did not call it? Can I save it as a method on an object and call it later when I need it?

+5
source share
3 answers

names.forEach is called an attempt to assign a return value to trim . Enabling it inside a function should work.

 var names = ["John", "Jen", "Tony"]; var obj = { prob: function () { for (var i = 0; i < names.length; i++) { document.write(names[i]); console.log(names[i]); } }, trim: function () {names.forEach(function(name) { document.write(name) console.log(name) })} } console.log("*********") console.log(obj.prob()); console.log("*********") console.log(obj.trim()); 
+8
source

Explanation of this behavior:

obj.prob assigned a function declaration and not called.

obj.trim sets up a call to the forEach .

This means that when you assign a property, you also call the code to run (this happens when you instantiate the obj object, which explains the initial registration of names)


Recommended Solution:

Include the forEach call in the anonymous function declaration (as in the for loop for the prob property):

 var names = ["John", "Jen", "Tony"]; var obj = { prob: function () { for (var i = 0; i < names.length; i++) { document.write(names[i]); console.log(names[i]); } }, // the code in this function block will only run // when trim is invoked trim: function(){ names.forEach(function(){ document.write(name); console.log(name) }); } }; 
+1
source

You just need to wrap your each function inside the function

 var names = ["John", "Jen", "Tony"]; var obj = { prob: function () { for (var i = 0; i < names.length; i++) { document.write(names[i]); console.log(names[i]); } }, trim: function(){ names.forEach(function(name) { alert(); document.write(name) console.log(name) })} } console.log("*********") console.log(obj.prob()); console.log("*********") 
0
source

Source: https://habr.com/ru/post/1263571/


All Articles