I have an API method in my nodejs app, in one of my controllers I am trying to generate pages on click, Unfortunately when calling the method my for loop does not reset values to default.
UPDATE
Here are my controllers
in my settings.js I have posts object
export const settings ={
posts: {
cnn: 2,
bbc: 4,
}
}
in my handlepPages.js I have this method;
export const getPages (doc, posts) =>{
let pages =[1,2,3,4]
for (let index = 0; index < pages.length; index ) {
doc.text(`${posts.cnn = 5}`)
console.log('posts.cnn', posts.cnn )
}
}
I am using this function getPages in my main controllers generatePages
import {settings} from './settings';
import {getPages} from './handlePages'
function generatePages(){
getPages(doc. posts)
}
calling generatePages on click, on console I get this;
posts.cnn 7
posts.cnn 12
posts.cnn 17
posts.cnn 22
Problem
calling again the method it does not start with posts default values it resumes from where it left
Expected results
Whenever I call my getPages function, my for loop should start with default posts values.
What am I doing wrong here?
CodePudding user response:
Whenever I call my getPages function, my for loop should start with default posts values.
Define the value inside the function, that way it gets declared and initialized each time the function is called instead of only once globally:
function getPages(doc){
let posts={
cnn: 2,
bbc: 4,
}
for (let index = 0; index < pages.length; index ) {
doc.text(`${posts.cnn = 5}`)
console.log('posts.cnn', posts.cnn )
}
}
Or, based on a comment on the question above...
in the real example the difference is just posts object is passed to getPages function getPages(posts)
In that case you can simply pass the values you want to the function:
getPages({ cnn: 2, bbc: 4 }, doc);
Or "reset" the value within the function:
function getPages(posts, doc){
posts.cnn = 2;
for (let index = 0; index < pages.length; index ) {
doc.text(`${posts.cnn = 5}`)
console.log('posts.cnn', posts.cnn )
}
}
Essentially, whatever the "real code" is doing... If you want the value passed to getPages
to always be 2
then either always pass a 2
to getPages
or immediately set the value to 2
inside of getPages
.