开发者

How can one put together multiple arrays into one string?

开发者 https://www.devze.com 2022-12-27 13:07 出处:网络
I\'m having a hard time describing what I\'m looking for. If we pretend that we\'re pulling an array (I\'ve used the .split to get user input data)

I'm having a hard time describing what I'm looking for.

If we pretend that we're pulling an array (I've used the .split to get user input data) where each line represents a link.

How can I then add an anchor tagg to that link that I'm pulling?

I need to be able to put

< a href=" + thearray + ">anything< /a>.开发者_运维技巧

The reason for this is that I'm dynamically creating a list.

I think that if I create two variables, one with this part

< a href="

one with the closing and then call some sort of function that puts those two and the pulled array in between them until the list is complete.

Does this make any sense?

edit: here's a link to the full code: http://hem.bredband.net/noor/thecode.txt


I think you mean this:

for(var x=0;x<thearray.length;x++) {
   document.write '<a href=" + thearray[x] + ">anything</a>'
}

You just want to loop through the array elements, wrapping them in some HTML.


Do you mean that you want to have an array like

["http://www.google.com", "http://www.yahoo.com", "http://www.stackoverflow.com"]

and you want to turn it into

"<a href='http://www.google.com'>anything</a>
<a href='http://www.yahoo.com'>anything</a>
<a href='http://www.stackoverflow.com'>anything</a>"

?

If so, you can just do

var myArray = ["http://www.google.com", "http://www.yahoo.com", "http://www.stackoverflow.com"];
var result = "";
for (var i=0; i<myArray.length; i++) {
   result += "<a href='" + myArray[i] + "'>anything</a>";
}

If not, thinking about "I want to start with X and end up with Y", with specific examples, might help you clarify your question.


Perhaps you mean something like this:

var tagStart = '<a href="',
    tagEnd = '">anything</a>',
    html = tagStart + thearray.join(tagEnd + tagStart) + tagEnd;

I would still suggest using a loop, though, since the code above will be unkind if thearray is empty.


I think using map and then join is going to be more readable:

function makeLink(url)
{
   return "<a href=\"" + url + "\">anything</a>";
}
result = myArray.map(makeLink).join("\n");

More info about map is available at http://www.tutorialspoint.com/javascript/array_map.htm

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号