How to focus on the final element in a JavaScript array

My function is almost there, but I am facing an issue:

function prevTrack() {
    if (playlist_index == (playlist.length - 0)) {
        playlist_index = -1;
    } else {
        playlist_index--;
    }
    playlist_status.innerHTML = playlist[playlist_index];
    audio.src = dir + playlist[playlist_index] + ext;
    audio.play();
}

I believe the error lies in the line playlist_index = -1;. Could someone please advise me on how to access the last item in the array? So it should be playlist_index = ???;

Answer №1

My memory is jogged of Python when setting the index to -1 in order to obtain the final element... nevertheless, this approach does not apply to JS. Instead, you must assign the index as playlist.length - 1.

Answer №2

It's my belief that

playlist_index = playlist.legth - 1

Answer №3

If the index is zero, would you like to set playlist_index to the last item in the array? Alternatively, if the index is greater than zero, should it be set to the first item in the array?

let playlist_index = (playlist_index === 0) 
  ? playlist_index = playlist.length - 1 
  : playlist_index--;

or

let playlist_index = (playlist_index === firstValueOfArray) 
  ? playlist_index = playlist.length - 1
  : playlist_index--;

Answer №4

It seems like you are attempting to create a loop that goes "around the world" while indexing. A simple way to achieve this is by using the modulo % operator.

const array = ['x', 'y', 'z']
for (let i = 0; i < 10; i++) {
  const element = array[i % array.length];
  console.log(element);  
}

Therefore, you can substitute

if (index == (array.length - 0)) {
    index = -1;
} else {
    index--;
}

with

index = (array.length + index - 1) % array.length;

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

React/Express: Error 413 encountered when posting due to payload size exceeding limit and Bodyparser failing to handle it

I've exhausted all options but this issue seems unsolvable. I have scoured every single suggested fix on stackoverflow and gone through 3 pages of Google search results. Methods I've attempted Inserted extended: true/false in bodyParser.json U ...

Extracting values from an event in Vue.js: A step-by-step guide

When working with Vue.js, I use the following code to fire an event: this.$emit("change", this.data); The parent component then receives this data, which is in the form of an object containing values and an observer. It looks like this: { data ...

Converting SQL table data into an array using JavaScript

I have some JavaScript code below that connects to a database and retrieves data from a table //Establishing database connection var sql = require("mssql"); var config = { user: '****', password: '*****', server: ' ...

Is it possible to access JSON with a numeric key and receive undefined as a result?

I've been attempting to extract information from my JSON data, but I keep getting an undefined result. Here is a snippet of my JSON: { "1": "A", "2": "B", "3": "C", "4": "D", "5": "E", "6": "F", "key":"pair" } This i ...

gcc error: there is a prohibition on function definitions in this location prior to the '{' token

I'm really stuck on this issue. Every time I try to move the function out of main and place it before main, I end up with even more errors. The error message I'm getting is: error: a function-definition is not allowed here before ‘{’ token ...

Utilizing multiple instances of fs.writeFile in Node.js

I am currently managing a hotel's check-in/out information on an http server in Node.js. I store all the JSON data in memory and write it to a file using "fs.writeFile". Typically, the data does not exceed 145kB, but when consecutive calls to fs.write ...

Can the Three.js WebGLRenderer be utilized on a node.js server environment?

There seems to be conflicting opinions on whether running WebGLRenderer on the server is feasible. Some say it can't be done, while others claim they are making efforts to achieve it but haven't succeeded yet. Is there a way to accomplish this? ...

Toggle checkbox fields based on link or checkbox selection

I need to create a functionality where specific checkbox fields (location fields) are shown or hidden based on the selection of the parent name. For example, if "United States" is selected, all US locations should appear below the United States label. I h ...

Utilizing Java Nashorn with WebEngine events

I'm having trouble processing events from a webEngine in Nashorn. Despite setting up the code to handle the "load" event, nothing is being printed or indicating that any events are triggering from the webEngine. #!/usr/bin/jjs -fx engine = (v=new(s=j ...

Using AngularJS to send a model to ui-select

Here is the scenario at hand: A form includes a directive known as <timeZone ng-model="formModel.timeZone" This directive communicates with a web service to fetch timezone information The directive then presents the timezones in a ui-select dropdown ...

In C#, swap out the odd elements in one array with the corresponding even elements from another array

int[] firstArray = new int[6] {2, 5, 7, 8, 9, 4}; int[] secondArray = new int[6] {4, 8, 2, 1, 5, 8}; I aim to swap odd elements in the first array with even elements from the second array. ...

No data appears to be populating the Javascript data list, yet no errors are being displayed in

I'm facing an issue where I have data that I'm using to create two arrays, but they both end up empty without any errors in the console. Below is the data: mydata = { "id": "661", "name": "some name", "description": "some desc", ...

Manipulating arrays in JavaScript

Currently, I am iterating through an array of waypoints fetched from the Google Maps API. Within this array, I need to retrieve the values labeled Xa and Ya. Right now, I'm accessing these values using [i]["location"]["Xa"], but the labels can vary (e ...

What is the best way to implement <li> in place of <div> to ensure the tool-tip code functions properly?

To see an example, please refer to this fiddle: http://jsfiddle.net/66nLy/12/ I am looking to achieve a similar functionality on a webpage, but using <li> instead of <div>. Here is the HTML code snippet: <table class="base-table selection- ...

I am experimenting with an express middleware that can either return next() or next("route")

After developing a middleware function that returns next() if a route's parameters are defined by queryItems, I came across a useful tool called node-mocks-http. However, it does not fake the next object. This led me to explore how this can be achieve ...

Concerns with the performance of Leaflet's polyline

Currently using Leaflet version 1.0.3 and encountering an issue with GPS positions on my map. Within a for loop, I am creating circle markers for each GPS position: var position = new L.latLng(lat, lng); coordinates.push(position); L.circle([lat, lng], ...

Parsing user input with a custom tokenizing function

As a C beginner, I'm currently facing an issue with tokenizing a "string" input in my code. Despite extensive manual review, I can't seem to pinpoint the bug. The goal is to tokenize the input for executing basic Linux commands as part of buildin ...

View content from an external file within an iframe

My goal is to showcase a text file within an iframe that updates automatically every second. To achieve this, I have created a simple function: function refresh() { $("#derek").attr('src', $("#derek").attr('src')); }; The automati ...

Facing difficulty in submitting form data with Reactjs

I am currently working on a project using Reactjs with nextjs. I am facing an issue where I am unable to receive any response or see anything in the console.log when trying to post form data. I have tried implementing the following code in index.js, but ...

Tips for modifiying date format in React app

I'm encountering an issue where I can't modify the date format, preventing me from displaying the date on the frontend. Currently, I'm utilizing the dateformat package. import dateFormat from "dateformat"; const EditFinancialInfo ...