简体   繁体   中英

How to append text to all values of javascript Array

Basically, I need to convert a string

"23423,1616,3461743,1345" 

to a string

"<img src='23423'></img><img src='1616'></img><img src='3461743'></img><img src='1345'></img>

So far I have tried:

    var PhotoArray=JSONeventobject.Events[i].FileNameArray.split(","); // Just convert this string to array

    for (i = 0; i < PhotoArray.length; i++) {
        PhotoArray[i] = "<img src='"+PhotoArray[i]+"</img>";
    }


            var Photostring = PhotoArray.toString().replace(",", "")

But this causes my browser to crash. It makes sense to me :/

Some terrible answers here. Try:

"1,2,3,4".split(",").map(function(a) { return "<foo>" + a + "</foo>"; }).join("");

Or with slightly more modern Javascript:

"1,2,3,4".split(",").map(a => `<foo>${a}</foo>`).join("");

Also please be aware of HTML injection .

You need to make sure you close your image tag. Another thing that may cause the problem is that i is undefined. Does your browser give an error message?

var str = "23423,1616,3461743,1345";
var PhotoArray = str.split(",");
for ( var i = 0; i < PhotoArray.length; i++ ) {
    PhotoArray[i] = "<img src=\"" + PhotoArray[i] + "\"></img>";
}
str = PhotoArray.join("");

If you don't want to use a loop (and I didn't want to use a loop), you could do this:

var str = "23423,1616,3461743,1345";

str = ("," + str + ",").split(',').join("'></img>,<img src='").split(",").slice(1,-1).join('');

console.log(str);

What it's doing is adding a comma on either side of the list, splitting the string into an array based on those commas, then adding the img tags on either side with the join call, splitting again based on the command between opening img tag and closing img tag we just put in, burning the first and last elements in the array, and then finally joining them all back together into a single string.

The console output is:

<img src='23423'></img><imgsrc='1616'></img><img src='3461743'></img><img src='1345'></img>

Nothing like an ugly one line solution!

There isn't an </img> tag in HTML, so you don't need that.

In PhotoArray[i] = "<img src='"+PhotoArray[i]+"</img>"; you're not ending the image tag, this will produce <img src='1616</img> which is why it gives strange results. Try PhotoArray[i] = "<img src='"+PhotoArray[i]+"'>"; instead.

#1    str.split([separator[, limit]])

split function splits a string into an array based on separator we give. limit is optional.

#2    arr.map(callback[, thisArg])

map function returns new array that is formed from result of calling "callback" function for each element in "arr". thisArg is optional.

#1    str.split([separator[, limit]])

join function joins all elements of an array, into a string. limit is optional.

So, answer is:

var photoString = "23423,1616,3461743,1345";
var photoArray = str.split(",").map(
    function(a) {
        return '<img src="' + a + '"></img>';
    }
).join("");

Sources: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join

In addition to what @mikel says --

You're using the same variable, i , as your index into JSONeventobject.Events and as your index into PhotoArray . Without seeing the rest of your code, I don't know whether that's going to be a problem, but it's worth checking.

Also, rather than converting to an array and back, it seems simpler to just write:

var Photostring = "<img src='" + JSONeventobject.Events[i].FileNameArray.replace(/,/g, "'/><img src='") + "'/>";

(that is, replace all the commas with '/><img src=' , prefix the first element's <img src=' , and append the last element's '/> ).

变量 ' i ' 是否声明为var

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM