I work with the text entered by the user, for a start I sort the line on the space, and then if the word is a link to the picture, I print it out, if not, I leave it in plain text and add it to the final message. Why, when executing a function, the argument in checkImage arr[i] becomes undefined and an empty link is obtained instead of a picture. I can not understand why the function does not see the element of the array?

 var text = document.getElementById("text1").value; var arr = text.split(" "); // делим строку по пробелу var mess = new Array(); // новое сообщение for (var i = 0; i < arr.length; i++) { if (arr[i].indexOf('.jpg') + 1 || arr[i].indexOf('.png') + 1 || arr[i].indexOf('.bmp') + 1 || arr[i].indexOf('.gif') + 1 || arr[i].indexOf('.jpeg') + 1) // если есть какое-либо расширение { checkImage(arr[i], // проверка ссылки, рабочая - картинка, нерабочая - // текст function() { var newr = document.createElement("a"); newr.href = arr[i]; newr.target = "_blank"; newr.innerHTML = '<img src= ' + arr[i] + ' style = "max-width:90%">'; f1.appendChild(newr); }, mess.push(" " + arr[i])) } else { mess.push(" " + arr[i]); } } var newr = document.createElement("div"); // создать и вывести текст newr.innerHTML = mess; f1.appendChild(newr); 

2 answers 2

Because the circuit. Inside callback

newr.href = arr [i];

i is not what you expect.

As part of ES6, you can use the let loop to not suffer from this regularly.

https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example

  • function checkImage (im_url, good, bad) {var img = new Image (); img.src = im_url; img.onload = good; img.onerror = bad; } - Maxkb24
  • Thank you very much, everything works, but for some reason in this code the link remains in the comment, I’ve put the comment in the check above, it turns out. that for working pictures and onload and onerror is performed - Maxkb24

Try using the checkImage function to call your function () function by passing arr [i] to it as an argument