Using a forEach loop to iterate through an array of strings in JavaScript

I have a collection of strings that I want to add to an empty string variable using a forEach loop. My goal is to print out each value separately without joining them together. However, when I try to achieve this by printing the values in the filltext once, it seems like something is not working as expected. Any ideas on what might be going wrong?

ch_labels = ['l', 'r'];

let ch = '';

let _ch_text = this.ch_labels.forEach(function(value) {
  console.log('channel names:', value);
  ch = value;
});

this.canvas.fillText(ch, 0, 0, 0);

console.log('names', ch);

Answer №1

Here is a code snippet you can use:

ch_labels = ['left', 'right'];

ch_labels.forEach(function(value, index) {
  console.log('channel names:', value);
  this.canvas.fillText(value, 0, index * 30);
});

This code will display your channel names vertically, one underneath the other.

Answer №2

In order to achieve the desired result, you should append the value to your variable ch instead of defining it separately. Here is how you can do it:

ch += value;

Furthermore, keep in mind that you cannot directly write to the canvas using canvas.fillText. Instead, utilize context in place of canvas.

Therefore, your revised code should look like this:

canvas = document.querySelector("canvas");
context = canvas.getContext("2d");

ch_labels = ['l', 'r'];

let ch = '';

this.ch_labels.forEach(function(value,index) {
  console.log('channel names:', value);
  this.context.fillText(ch, (index+1)*30, 10 );
  ch += value;
});

console.log('names', ch);
<canvas width="200" height="200"></canvas>

Answer №3

ch_labels = ['left', 'right'];

let ch = '';

let _ch_text = this.ch_labels.forEach(function(name) {
  console.log('channel names:', name);
  ch += name;
});

console.log('combined names:', ch);

It seems the issue arose from reassigning the value. To avoid this, you can use either ch = ch + name or the shorter version ch += name.

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

The stylesheet failed to load due to an incorrect MIME type (text/html instead of text/css)

As I delve into creating a personal project centered around a basic expense tracker web app, I encountered an obstacle right at the start of my journey. The main page's stylesheet (index.html) refuses to load, resulting in the common error message: Th ...

Guide on adding multiple values to a single key in JavaScript

I am working with an object array called var codropsEvents={[date1]:['event1'],[date2]:['event2'}; My goal is to add multiple values to event1, such as {[date1]:['event1','event2'],..} To achieve this, I have written ...

The success function in Ajax Jquery is not triggering

I am facing an issue with my jQuery code where it always triggers the error function: function getStatistic6() { var response; var allstat6 = []; var dstart = "01.01.2014"; var dend = "03.31.2014"; $.ajax({ type: 'GET', url: 'http: ...

I am attempting to calculate the quantity of divs with a specific class, but for some reason, the .length method is consistently returning a value of 0

I'm having trouble counting the number of div elements with a specific class. Every time I use .length, it comes back as 0. What could be causing this issue? var keyspressed keyspressed = $('.key').length; console.log(keyspress ...

My Node.Js app refuses to run using my computer's IP address, yet works perfectly with localhost

My Node.js application is set up to listen on port 5050 of my machine: Visiting http://localhost:5050/myapp loads the app successfully. I am using the Express framework, so my listening framework looks like this: var server = app.listen(5050, '0.0.0 ...

Having trouble displaying ES6 promise value in AngularJS view

Currently, I am working on a project where I am utilizing the Pinterest JavaScript SDK to retrieve some pin data. In order to achieve this, I have created a Pinterest service with a method that is invoked in my HomeController. To fetch the response and d ...

Removed specific rows from JQuery Datatables

How can I remove selected rows from a DataTable that is using a local array for data? Here is how my table was set up: var selected = Array(); var dataSet = []; var rowItem = ""; $(document).ready(function () { var table = $("#tabl ...

Error: The NgTable in AngularJS is not defined when reloading the page

I have successfully implemented Angularjs NgTable with pagination inside a tab provided by Angularjs Material in various parts of my project. However, I am facing an issue where I am unable to reload the tables in this particular case. I am unsure of what ...

Extracting JavaScript OnClick button using Selenium

I'm having trouble extracting the email address from the following URL: https://www.iolproperty.co.za/view-property.jsp?PID=2000026825 that is only visible after clicking on the "Show email address" button. However, every time I attempt to click and r ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

How to include an image in a CSS file for a React project

I'm attempting to use an image from public/assets/subtract.png, but I am encountering a resolution issue. Here is the code snippet in question: body { background-image: url("./assets/subtract.png"); } The specific problem I am facing is ...

Using AngularJS to dynamically update an array of objects in response to a selection change

I am facing a challenge with two dynamic object arrays: one for colors and one for buses. The main objective is to assign a color to each bus. I have used ng-repeat to create selects for each color, and employed ng-change to call the updatebus function, pa ...

Angular - implementing a click event at the beginning of your application

I am trying to attach a click event to all li (list) elements within an ordered list in my Angular controller. However, for some reason, the event is not working as expected. Here is a snippet of the code where I am attempting to set up this event: $docum ...

Update the HTML card with dynamic content by retrieving information from an overlay

I am working on creating an HTML card that will display input values and images from an overlay. I require assistance with transferring data from the overlay to the card Populating the data and image in the card similar to the example below. A sample of ...

Using the .space directive in MIPS to create a For Loop

I've been working on a loop that fills an array with user-inputted integers until it's full. However, every time I enter a value, QTSPIM outputs 268501016, which seems to be some random register value. To check if the loop was functioning correc ...

Get answers for AngularJS ng-repeat by initializing inputs with the corresponding answer object

I have a set of questions coming from an AJAX response that I am displaying using ng-repeat. Each question input in the list needs to be connected to a separate answers array through its ng-model. Here is an example of how the question array looks: booki ...

What is the best way to develop shared singleton components that work seamlessly across various platforms?

How about developing a React component called LoadingMask that can toggle the display of a loading mask based on the current state? The purpose would be to show the mask before an ajax call and hide it once the data is received. To avoid showing multiple ...

Velocity: The initial parameter was not recognized as a property mapping

I've been experimenting with Velocity for animations (without jQuery), but I'm running into an issue where I keep getting this error message: Velocity: First argument ([object HTMLDivElement]) was not a property map, a known action, or a regis ...

Resizing an image for mobile using next/Image

I have been using next/Image in conjunction with tailwind to display an image as a banner that spans the entire width of its container, which happens to be the full page width. The challenge I am facing is that the image appears distorted and unbalanced o ...

Stop the Decimal in MUI TextField

Having trouble creating a customized Currency Input? You may be experiencing an issue where the textfield prevents the input of decimals. Take a look at the code below for possible solutions. main.ts const [_val, setVal] = React.useState(""); const h ...