PiR
PiR

Reputation: 37

Javascript Create audio tag from array

I have an array of musics like that:

var files=["song1.mp3","song2.mp3","song3.mp3", "song4.mp3"]

And I want to display all on audio tag, I've done this but it doesn't work.

for (var in files){
$("body").append($("<audio> <source src="+"/audio/" + element" type='audio/mpeg'></audio>"));}

Can you help me please.

Upvotes: 1

Views: 510

Answers (2)

Adrian
Adrian

Reputation: 8597

Inside the for loop, you don't need to include a variable declaration. Your loop should look like this:

for(element in files)
{
   $("body").append($("<audio> <source src='/audio/" + element + "' type='audio/mpeg'></audio>"));
}

Note I have added an extra + sign and changed the brackets order and type for the src tag.

Upvotes: 0

j6s
j6s

Reputation: 81

In this example your loop is incorrect. To loop over arrays you can use one of the following methods:

  1. for loop using array length: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length

    for (var i = 0; i < array.length; i++) { /* array[i] is your item */ }

  2. Array.forEach: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

    array.forEach(function(item) { /* item is your item */ }

  3. for of loop: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of

    for (item of array) { /* item is your item */ }

Note, that you will have to check the supported browsers for the last two methods.

Upvotes: 2

Related Questions