Determine the maximum array size in Javascript

Having trouble setting a limit in my custom lightbox for a gallery

    <script>


var imagenumber = 0;

    function btnleft(){
        load = imagenumber-=1;
        document.getElementById('lightboxcontent').innerHTML=imagelist[load];

        }

function btnright(){
    load = imagenumber+=1;
    if (load==undefined){load=imagenumber-=1}
    document.getElementById('lightboxcontent').innerHTML=imagelist[load];
    }
</script>

Here is the array

var imagelist=new Array(); // regular array (add an optional integer
imagelist[0]="image1.jpg";       // argument to control array's size)
imagelist[1]="image2.jpg";
imagelist[2]="image3.jpg";

After clicking the next button more than 3 times, I receive the error message "undefined". What is the best way to set a limit on my arrays?

Answer №1

Give it a shot!

 function btnMoveLeft(){
    var display = imagelist[imagenumber-=1];
    if (display) // ensure index is within array bounds
        document.getElementById('lightboxcontent').innerHTML = display;
    else
        imagenumber = 0;
 }
 function btnMoveRight(){
    var display = imagelist[imagenumber+=1];
    if (display) // ensure index is within array bounds
        document.getElementById('lightboxcontent').innerHTML = display;
    else
        imagenumber = imagelist.length-1;
 }

Remember, Arrays in JavaScript do not have a fixed size, they behave more like infinite lists. It's difficult to limit their length, especially using the constructor, as the number argument is only for initialization.

You can utilize the length property of an array to ensure your index is within bounds:

i >= 0 && i < arr.length
. My code simply verifies if there is an item at that index (as your second function also aims to do) and resets the index if needed.

Answer №2

It appears that the action triggered by the "next button" is calling the btnright() function.

If this is indeed the case, then the check for undefined is incorrect. You may want to modify your function as follows:

function btnright(){
  load = imagenumber += 1;
  // Ensure you are checking the value within the array, not just the index variable.
  if (imagelist[load] === undefined) {
    load = imagenumber -= 1;
  }
  document.getElementById('lightboxcontent').innerHTML = imagelist[load];
}

However, from a stylistic perspective, there is room for improvement. The load variable is redundant as it always mirrors imagenumber. Consider refactoring the function as shown below:

function btnright() {
  // If the next array value exists, proceed.
  if (imagelist[imagenumber + 1] !== undefined) {
    // Increment the index and display the new image.
    document.getElementById('lightboxcontent').innerHTML = imagelist[++imagenumber];
  }
}

function btnleft() {
  // If we are not on the first image, proceed.
  if (imagenumber !== 0) {
    // Decrement the index and display the new image.
    document.getElementById('lightboxcontent').innerHTML = imagelist[--imagenumber];
  }
}

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

Mastering advanced authentication with Passport and the JwtStrategy

During a recent project I downloaded from the internet... In one specific part of the code, the following is implemented: passport.use(new JwtStrategy({ secretOrKey: credentials.secret, jwtFromRequest: ExtractJwt.fromAuthHeader(), }, ...

The render() method of the component is failing to execute even after the mobx store value has been updated

After successfully updating the store before fetching data from the server, everything seems to be working fine. However, once the data is fetched and the store is updated again, the render() method does not get called. Check out this code snippet @acti ...

Pressing the reset button will initiate once the loader has finished

Hello everyone, I'm currently working on creating a button that transforms into a loader when submitted and then reverts back to a button after the form is successfully submitted. I suspect the issue lies within my JavaScript. I'm not sure how ...

Using Vuejs to implement pagination on a weekly basis

I need some help with Vue pagination. I have a ticket object, and currently, it displays in a certain way. What I'm trying to achieve is to display the tickets weekly. For example, if this week is the 31st week of the year, then from today until Sunda ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

Can the installation of Canvas be done on a device with the M1 chip?

When attempting to install canvas on a MacBook Pro M1 using the command: npm install --save-dev canvas An error is displayed: npm ERR! code 1 npm ERR! path /Users/xiaoqiangjiang/source/reddwarf/frontend/js-wheel/node_modules/canvas ... (error message con ...

Creating a hierarchical JSON structure to populate a Handlebars template (HTML) for an iterative component, allowing for the display of three levels of interconnected

Currently, I am working on developing a mega menu component that involves three levels of content. Level 1 (L1): This level is displayed horizontally in a traditional navbar. When hovered over, it expands to reveal the mega menu. Level 2 (L2): These item ...

Utilize React and Django to showcase encoded video frames in your application

Having recently ventured into the world of web development, I've been facing a challenging problem that I can't seem to crack. My tech stack involves the use of React and Django. The issue at hand is with a 3rd party application that utilizes op ...

Choosing CSS/JS selector: Pick the final element with a class that does not match

My goal is to extract the most recent td element from the latest tr within an HTML table, ensuring that the latest td does not belong to the disabled class. I am attempting to achieve this using pure JavaScript with CSS selectors (without relying on jQuer ...

Encountered a JavaScript error while using Internet Explorer

My web and Jquery plugins are working flawlessly on various browsers such as Firefox, Chrome, Safari (Windows & OSX), and Android. However, they encounter issues with Windows and Internet Explorer as some JavaScript fails to load. It's frustrating tha ...

Uniquely tag an uploaded file

My code for uploading files is as follows: var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", uploadProgress, false); xhr.open("POST", requestUrl, true); xhr.send(f); I want to draw your attention to the fact that I have attached a l ...

AngularJS: Handling multiple asynchronous calls simultaneously in a function

In my AngularJS function, I need to make two asynchronous calls that are independent of each other. However, the function should only return when both calls have completed and the results are stored in the return variable. I have tried various solutions a ...

Working with Java to parse non-strict JSON data that does not have keys enclosed in quotes

I am currently facing the challenge of parsing a string in JSON format where keys are not enclosed in quotes. While I have successfully parsed this string in Javascript, I am struggling to find a Java API that can assist me with parsing. The APIs I have at ...

Is there a way to keep the node text in place and prevent overlapping in my D3.js tree?

I'm facing an issue with long text strings in my D3 tree. The nodes move according to the tree structure, but how can I handle excessively long node-text? For instance, if the label "T-ALL" had a longer name, it could overlap with the neighboring nod ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

Solving Angular Circular Dependencies

My popupservice allows me to easily open popup components: export class PopupService { alert() { this.matdialog.open(PopupAlertComponent); } yesno() { this.matdialog.open(PopupYesNoComponent); } custom() { this.matdialog.open(PopupCustomCompon ...

Avoid the automatic scrolling of a datatable to the top when clicking on a button within a column using jQuery

https://i.sstatic.net/Jx5G6.png Is there a method to stop the datatable from automatically scrolling to the top when any of the buttons is clicked? ...

Tips for surviving a server restart while using sequelize with a postgres database and handling migrations

Within my express application, I utilize Sequelize for database management. Below is the bootstrap code that I use: db.sequelize .sync({ force: true}) .complete(function(err) { if (err) { throw err[0]; } else { //seed requi ...

Update the useMemo state value after the initial function block has been executed

Currently, I have a list of characters from Dragon Ball Z that users can filter based on gender, race, or both using useMemo. let dbzCharacters = useMemo<CharacterObj[]>(() => { if (filterGenderValue && filterRaceValue) { retur ...

Retrieving multiple rows from an array using PHP and MySQL

I am looking for a way to send notifications to multiple users on my website. I have their IDs stored in an array called $userinput, where each ID is separated by a comma (e.g., "7,1,2,3"). My goal is to execute the following query: $sqlnot = "INSERT INT ...