array work at the for loop with try catch? (node.js and javascript) i got error 'ReferenceError: p is not defined'

array work at the for loop with try catch (node.js and javascript) i got error ‘ReferenceError: p is not defined’

the code is

  for(var i = 0; i<12; i++ ){   try{     var incre = i;     var name = 'pic'+ incre.toString();     p[i] = req.files[name][0].path;   } catch (error) {     p[i] = null;   }}; 

i got error ‘ReferenceError: p is not defined’ node server say ‘p’ is problem which this array. it is process of insert multer path at each array which is p[1] p[2] p[3] …. [p11]

Add Comment
2 Answer(s)

    You need to declare p.

    let p = []; // Add this line  for (var i = 0; i < 12; i++) {    try {      var incre = i;      var name = 'pic' + incre.toString();      p[i] = name;    } catch (error) {      p[i] = null;    }  };    console.log(p)

    Professor Answered on October 26, 2020.
    Add Comment

      Try to declare the array p outside the loop and inside the loop set the values for the array, like this

      let p = []    for (var i = 0; i < 12; i++) {    try {      var incre = i;      var name = 'pic' + incre.toString();      p[i] = req.files[name][0].path;    } catch (error) {      p[i] = null;    }  };    console.log(p)

      Professor Answered on October 26, 2020.
      Add Comment

      Your Answer

      By posting your answer, you agree to the privacy policy and terms of service.