What is the optimal method for iterating through every element in a string array?

Within my code, I am dealing with an array named

var mya = ["someval1", "someotherval1", "someval2", "someval3"];
. The goal is to have a function that receives an object with a property set to one of these values.

Instead of simply iterating over the array using a for loop, it might be more efficient to utilize a switch statement considering the static nature of the array and the specific tasks associated with each property.

I am trying to implement this functionality using a switch statement in the following pseudo code:

switch(mya.forEach) { 
    case "someval1": 
        alert("someval1"); 
        break; 
    ... 
    default: 
        alert("default"); 
        break; 
}

However, this code snippet only executes once.

It seems that there may not be a simpler way to combine a forEach loop and a switch statement as desired.

Answer №1

for( var j=0; j<myarray.length; j++ ){
    switch( myarray[j]) { 
        case "value1": 
            alert("value1"); 
            break; 
        ... 
        default: 
           alert("default value"); 
           break; 
    }
}

Answer №2

The reason why switch cannot be used in place of foreach is because they serve different purposes.

for (var j in myArray)
{
    switch (myArray[j])
    {
        ...
    }
}

Answer №3

Since you are considering using the forEach method, it seems like you are not too worried about compatibility with older browsers. In that case, a better approach would be to utilize the Array.indexOf() method:

var mya = ["someval1", "someotherval1", "someval2", "someval3"],
    returnedFunctionValue = returnRandomValue();

console.log('Searching for: "' + returnedFunctionValue + '."');

if (mya.indexOf(returnedFunctionValue) > -1) {
    // the value held by the returnedFunctionValue variable is contained in the mya array
    console.log('"' + returnedFunctionValue + '" at array-index: ' + mya.indexOf(returnedFunctionValue));
}
else {
    // the value held by the returnedFunctionValue variable is not contained in the mya array
    console.log('"' + returnedFunctionValue + '" not held in the array');
}

Check out a simple demonstration on JS Fiddle.

Alternatively, you could also use Array.prototype.forEach (for modern browsers):

var mya = ["someval1", "someotherval1", "someval2", "someval3"],
    returnedFunctionValue = returnRandomValue();

mya.forEach(function(a, b){
    if (a === returnedFunctionValue) {
        console.log('Found "' + returnedFunctionValue + '" at index ' + b);
    }
});

Another demo on JS Fiddle.

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

Combining AngularJS with ng file upload and Sails JS for seamless file uploading

When I upload a file, I also need to send some additional information along with it. The instructions mention using the data parameter for this purpose, but I'm having trouble accessing it in my Sails controller action. Frontend: Upload.upload({ url ...

What is the method for defining unassociated variables in Angular?

I am currently seeking a solution to retrieve data from the server (or JSON file) and store it in two separate variables: 'firstVariable' for manipulation purposes, and 'secondVariable' for storing the original unaltered data. However, ...

What is the best way to loop through an array of JSON data in order to consistently retrieve the initial JSON object?

How can I retrieve only the full highlight videos from the JSON object in the video array? { "response": [ { title: "United vd Chelsea", "videos": [ { "title": "Highlights&quo ...

A guide on implementing nested child routes in AngularJS 2

I have successfully completed routing for two children, but now I want to display nested routes for those children. For example: home child1 child2 | grand child | grand child(1) ...

When running the test, the message "Unable to resolve all parameters for BackendService" is displayed

Upon executing the ng test command, the following error was displayed. This is my service specification: describe('BackendService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { p ...

Delayed execution not completely cancelled prior to component being unmounted

Alert: Avoid calling setState (or forceUpdate) on an unmounted component. While this won't cause any issues, it could suggest a memory problem in your application. Make sure to clean up all subscriptions and async tasks in the componentWillUnmount met ...

Extract data from nested JSON and populate a list with corresponding values

<ul> <li><a href="" class="edit">a unique item in the list</a></li> <li><a href="" class="edit">another unique item in the list</a></li> <li><a href="" class="edit">yet another unique ...

What is the best way to update this payload object?

Currently, I'm developing a route and aiming to establish a generic normalizer that can be utilized before storing user data in the database. This is the function for normalization: import { INormalizer, IPayloadIndexer } from "../../interfaces/ ...

How can I use a JavaScript function to remove an element from a PHP array?

Imagine I have a PHP session array: $_SESSION[MyItems]=Array('A'=>"Apple", 'B'=>"Brownie", 'C'="Coin")) which is utilized to showcase items on a user's visited page. I want the user to have the ability to remove o ...

Error found in Paper.js at line 81: Uncaught TypeError - Unable to access properties of undefined (specifically '1') while utilizing Material UI and Joy UI

I am encountering an issue while using react js with material UI and JoyUI, where I am getting a blank screen. Below is the code snippet causing the problem: import React from 'react'; import { CssVarsProvider } from '@mui/joy/styles'; ...

Player-Oriented Online Game: Addressing Target Accuracy Challenges in ctx.setTransform

I'm currently developing a web game and my goal is to ensure that the player remains at the center of the screen. However, as the player moves further away from the center, the accuracy decreases. I've attempted using ctx.setTransform, which work ...

Discovering Ways to Navigate and Search Within XML and JSON Data

Currently, I am receiving a balance sheet report in the form of a JSON or XML object. The JSON format resembles the Row object containing several nested arrays. Among these are different RowTypes such as Header, Section, and Summary Row. My goal is to iden ...

Having difficulty displaying elements from two arrays at particular intervals

I am currently working with two arrays that have the same number of items in each. My goal is to print these items in intervals within the console. The desired output would look something like this: 1 Bruce Wayne 45 Then, after a one-second interval, it s ...

How can I send data in JSON format to a JavaScript AJAX request?

I've created a method that looks like this: public String getUTResult() throws IOException { BuildResultParser bp = new BuildResultParser(); BuildResultBean b = bp.getreadFile("C:\\bc.txt"); String str = b.getuTresult(); ...

Continuously send HTTP requests to the page until receiving a status code of 200, then proceed to redirect to the same page

I am new to JavaScript and seeking advice on how to tackle this task. I have attempted the following approach, but it is not functioning correctly: while (status !== 200) { checkPage(); } function checkPage() { var xhr = new XMLHttpReque ...

Visit a webpage on my site

Is it feasible to embed a website within another website? Suppose I have my index.html file. What if in the center of that file, we include an iFrame or similar element that loads , allowing users to explore Google directly on my website? ...

Updating website content dynamically using Javascript and JSON-encoded data

My programming code seems to be acting oddly. I have structured my data in a JSON object as follows: injectJson = { "title": "Champion Challenge Questions", "rules": [ { "idChrono": "chrono-minute", "text": "Top is missing!", ...

A guide on extracting content from a PDF file with JavaScript

Hey there, I'm experimenting with various methods to extract content from a PDF file but so far nothing seems to be working for me. Even when I try using pdf.js, it shows an error and I can't figure out why. This is the approach I've been tr ...

Next.js - Anticipated that the server HTML would include a corresponding <div> within <div> tag

For a live demonstration, please click here In my current project, I am experimenting with creating a simple layout that adjusts based on the user's screen size. Specifically, on mobile devices, only the latest posts should be displayed. On desktops, ...

Using the result of one function in another function when using async await

I am facing an issue with running a function based on the return value of another function: // in utils.js methods:{ funcOne(){ // do some thing return true } } //in component.vue methods:{ funcTwo(){ let x = this.funcOne() if(x){ ...