javascript pull data from an array

As a novice in HTML and JavaScript, I have a brief code snippet that embeds multiple audio files. I am utilizing a loop and would like to utilize strings from an ARRAY as the sources for the WAV files (rather than just "file1.wav"). Thank you.

<!DOCTYPE html>

    <html>
    <body>
    <p id="demo"></p>

<script>
    var AudioFiles = [
    "file1.wav",
    "file2.wav",
    "file3.wav",
    ];

    for(var i = 0; i < 3; i++){
      document.body.innerHTML = document.body.innerHTML + `
          <audio controls>
            <source src="file1.wav"; type="audio/wav">
          </audio>
      `
    };
</script>

    </body>
    </html>

Answer №1

To achieve this, you can utilize string interpolation and array index lookup, especially if you are working with ES6.

<script>
    var audioFiles = [
    "file1.wav",
    "file2.wav",
    "file3.wav",
    ];

    for(var i = 0; i < 3; i++){
      document.body.innerHTML = document.body.innerHTML + `
          <audio controls>
            <source src="${audioFiles[i]}"; type="audio/wav">
          </audio>
      `
    };
</script>

Nevertheless, there are a few points worth mentioning:

Firstly, it is standard practice not to start variable names with capital letters. So, it would be better to use audioFiles instead of AudioFiles. Capitalization is typically reserved for classes and constructors.

Secondly, directly appending elements into the DOM in the manner shown may not be the most optimal approach. Consider using the appendChild function: https://www.w3schools.com/jsref/met_node_appendchild.asp

Thirdly, you can simplify the process by utilizing the forEach function, eliminating the need for a manual counter, which enhances readability and reduces potential errors:

<script>
    var audioFiles = [
      "file1.wav",
      "file2.wav",
      "file3.wav",
    ];

    audioFiles.forEach(function(item) {
      document.body.innerHTML = document.body.innerHTML + `
          <audio controls>
            <source src="${item}"; type="audio/wav">
          </audio>
      `
    });
</script>

This method will iterate over each item in audioFiles, passing it as item to the iterator function.

However, there's an even more efficient way...

<script>
    var audioFiles = [
      "file1.wav",
      "file2.wav",
      "file3.wav",
    ];

    document.body.innerHTML =
      document.body.innerHTML +
        audioFiles.map(function(item) {
         return `
          <audio controls>
            <source src="${item}"; type="audio/wav">
          </audio>
      `}).join();
</script>

By using the map function, we reduce repetition and minimize potential mistakes.

The map function transforms an array into another array based on the iterator function provided.

Answer №2

When using template literals, make sure to utilize the syntax ${variable} for embedding external variables in your string.

for(let j = 0; j < 4; j++){
  document.body.innerHTML = document.body.innerHTML + `
      <video controls>
        <source src="${VideoFiles[j]}"; type="video/mp4">
      </video>
  `
};

Answer №3

let audioList = ["file1.wav", "file2.wav", "file3.wav"]; //list of audio file paths
let htmlContent = audioList.map(audioPath => {
    return ` 
    <audio controls>
      <source src="${audioPath}"; type="audio/wav">
    </audio>`;
}).join(""); /*create HTML content for updating - remember to join(""),
since map returns an array*/
document.body.innerHTML += htmlContent;

This approach only updates the DOM once.

Answer №4

To display audio files in a loop, simply access the array elements using their index.

var SongCollection = [
"song1.mp3",
"song2.mp3",
"song3.mp3",
];

for(var j = 0; j < 3; j++){
  document.body.innerHTML = document.body.innerHTML +'<audio controls><source src="'+SongCollection[j]+'"; type="audio/mp3"></audio>'
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for resolving the "trim" of undefined property error in Node.js

Looking to set up a basic WebAPI using Firebase cloud functions with express and TypeScript. Here's the code I have so far: import * as functions from 'firebase-functions'; import * as express from 'express'; const app = express( ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Ways to conceal the jqgrid thumbnail

I have a jqgrid that displays a large amount of dynamic data. I am looking for a way to hide the thumb of the vertical scrollbar in the jqgrid when scrolling using the mousewheel. Here is a basic example: var data = [ [48803, "DSK1", "", "02200220", "O ...

The date entered in an HTML input is being interpreted as "incorrect" by the system

Upon inputting 3/15/2019 as the date and then checking the time with console.log(fromDate), the output appears as Thu Mar 14 2019 19:00:00 GMT-0500 (Central Daylight Time). Why is it not showing Fri Mar 15 2019 00:00:00? Could this be related to the tim ...

What is the best way to utilize an "as" property in TypeScript when forwarding props to a component?

I am currently working on creating a collection of components, and I require some of them to have the option of a customizable tag name. For instance, there are times when what seems like a <button> is actually an <a>. Therefore, I would like t ...

Reconfigure an ancestral item into a designated key

I have a single object with an array of roles inside, and I need to transform the roles into an array of objects. See example below: Current Object: displayConfiguration: { widgetList: { widgetName: 'widget title', entityType: 'As ...

Using Vue.js to display svg content inside the <svg> element

One of my Vue.js components is responsible for dynamically building the content of an svg element. Let's simplify things and say that the content consists of a <circle cx="50" cy="50" r="60" /> This component achieves this by manipulating a dat ...

What is preventing Web API from triggering a CORS error in browsers such as Chrome and Edge, as well as the Postman tool?

While working on developing an API in Asp.Net Core 3.1, everything seemed to be functioning properly. However, I encountered CORS-related errors when attempting to send requests via ajax. Interestingly, these errors were not present when sending GET reques ...

Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

How can I attach an addEventListener to the parent element in Vue 3.x? I discovered that you can access the parent by using this code: import { getCurrentInstance, onMounted } from 'vue' onMounted(() => { console.log(getCurrentInstance() ...

Offering fields for modules, main, and browser that meet the needs of ESM, CommonJS, and bundlers

I have upgraded a number of my published npm packages to include both commonjs and esm builds. Some of these packages are meant for use in both node and the browser, and they are all compiled using webpack or rollup. Additionally, all of them are written i ...

Clicking on hyperlink within email to open in default web browser

I am facing a problem with my Angular web app. Here is the scenario of the issue: When I send a link to my app via email and try to open it from a mobile email client using a short version of a browser or webview (not sure what it's called), I encou ...

Sidebar navigation text shifting during transition

I attempted to modify the CSS and JavaScript, but unfortunately, it had no effect and actually caused more issues. I adjusted the position and display properties in the CSS, but it seems that wasn't the root of the problem. If anyone could offer assis ...

What is the best method to activate a button only when the appropriate radio buttons have been chosen?

Just dipping my toes into the world of javascript. I've created a form with a set of "Yes/No" radio buttons, and I attempted to create a function that will disable the "Submit Form" button if any of the following conditions are met: If one or more r ...

Is it possible to utilize a controller within a different controller?

As I work on developing an application, I am faced with the challenge of using controller functions within another controller function. Is it possible to achieve this or not? Use-case: My goal is to verify in the User collection (using mongoDB) if a user ...

How can I hover over multiple cells in a table?

Is there a way to change the color of multiple adjacent cells when hovering over one cell, and can this be done dynamically (so the number of adjacent cells that change color can vary)? Here is the code snippet: I'm using React to create a table wit ...

Send the content of an HTML file to a JavaScript variable

I'm working on using a template.html file as an email template in loopback/nodejs. In PHP, I know how to include the template.php file and store it in a variable like this: ob_start(); include template.php; $template = ob_get_clean(); Is there a way ...

Using JavaScript variables in CSS: a beginner's guide

My website features a typewriter effect, but I want the animation to match the length of the words exactly. I attempted using JavaScript variables in CSS, but unfortunately, it's not functioning properly. Could someone please advise me on how to remed ...

Automatically, the "ng-hide" class gets added despite using the correct syntax for ng-show

I am trying to dynamically show/hide a tr tag within a table based on the value of a scope variable in the controller. Despite writing the code correctly, I am facing an issue where the "ng-hide" class is automatically added to the tr tag every time it is ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

Quick Validator. Establishing a schema that relies on specific values

I have a situation where I need to differentiate between two types of users - teacher and student. The schema for a teacher looks like this: { username : string; firstName : string; lastName : string; type : 1; // 1 = teacher schoolId : o ...