Reputation: 5
Currently I have an array "teenused" that contains a'la: "01","01","03","04","05","06","07" I call function grindTeen in my code.
Code and functions are here:
function grindTeen(teenused) {
for (var i = 0; i < teenused.length; i++) {
var arrayItem = teenused[i];
return('<img src="/bena/design/icons/B-icons-'+arrayItem+'.png" width="33" height="33">');
}
};
The function should return a string with html image src
in it.
Appearently I'm noob in JavaScript Any suggestions how to do it better?
In my case I was so noob that I did not underestand that from XML I got back String not Array - so here's the correct solution with converting string to array: http://jsfiddle.net/SQQbe/13/
Upvotes: 0
Views: 82
Reputation: 7466
As of now, your loop only iterates once because you have return
statement in there, that returns the value from the function. What you need to do is store the results and then return them in the end.
function grindTeen(teenused) {
var images = [];
var arrayItem = null;
for (var i = 0; i < teenused.length; i++) {
arrayItem = teenused[i];
images.push('<img src="/bena/design/icons/B-icons-'+arrayItem+'.png" width="33" height="33">');
}
return images;
};
var teenImages = grindTeen(teenused);
// take the items in the teenImages list and make it into a string separated by space
var teenImagesHtml = teenImages.join(' ');
You can read more about .join()
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/join
Here's the working fiddle: http://jsfiddle.net/amyamy86/V4Rwh/
Updated:
For array ['01', '02', '03', '04', '05', '06']
the output will be (if put into the <div>
):
<div id="c">
<img src="/bena/design/icons/B-icons-01.png" width="33" height="33">
<img src="/bena/design/icons/B-icons-02.png" width="33" height="33">
<img src="/bena/design/icons/B-icons-03.png" width="33" height="33">
<img src="/bena/design/icons/B-icons-04.png" width="33" height="33">
<img src="/bena/design/icons/B-icons-05.png" width="33" height="33">
<img src="/bena/design/icons/B-icons-06.png" width="33" height="33">
</div>
Upvotes: 1