The for loop in JavaScript fails to verify the contents of an array and instead shows a message in a designated

The message for leap year is not appearing in the designated element

Uncertain why the message isn't showing after the for loop

const year = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032];

for (var i = 0; i < year.length; i++) {
  if ((year[i] % 100 === 0) || (year[i] % 100 != 0) && (year[i] % 4 == 0)) { //Iterates through the 'year' array
    document.getElementById('results').innerHTML = year[i] + " is a Leap year" + "<br>"); //inserts the message into the inner HTML of ID results
} else {
  document.getElementById('results').innerHTML = year[i] + " is not a Leap year" + "<br>"); //inserts the message into the inner HTML of ID results
}
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Leap Year Array</title>

  <style>
    body {
      background-color: powderblue;
      text-align: center;
    }
  </style>

</head>

<body>
  <h1>Check Leap Year from an Array List</h1>
  <br>
  <p>This is my Array List: 2020, 2021, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032</p>
  <p>Result:</p>
  <p id="results"></p>

</body>

Answer №1

Your code is riddled with syntax errors that are preventing it from running smoothly. There are additional characters like `)` at the end of `innerHTML` assignments and extra `}` brackets scattered throughout.

Additionally, the conditions in your `if` statement are not grouped correctly.

Remember, to append to the DIV, you should be using `+=` instead of `=`, which replaces the existing `innerHTML` content.

Furthermore, in your `if` condition, the exception criteria should be multiples of 400 and not 100.

const year = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032];

for (var i = 0; i < year.length; i++) {
  if (year[i] % 400 === 0 || (year[i] % 100 != 0 && year[i] % 4 == 0)) { //Loops through the array 'year'
    document.getElementById('results').innerHTML += year[i] + " is a Leap year" + "<br>"; //add the message to the inner HTML of ID results
  } else {
    document.getElementById('results').innerHTML += year[i] + " is not a Leap year" + "<br>"; //add the message to the inner HTML of ID results
  }
}
<!DOCTYPE html>
<html lang="en" dir="ltr>

<head>
  <meta charset="utf-8">
  <title>Leap Year Array</title>

  <style>
    body {
      background-color: powderblue;
      text-align: center;
    }
  </style>

</head>

<body>
  <h1>Check Leap Year from an Array List</h1>
  <br>
  <p>This is my Array List: 2020, 2021, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032</p>
  <p>Result:</p>
  <p id="results"></p>

</body>

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

Best practices for including jQuery in ASP.NET (or any other external JavaScript libraries)

Can you explain the distinctions among these three code samples below? Is there a preferred method over the others, and if so, why? 1.Page.ClientScript.RegisterClientScriptInclude(typeof(demo), "jQuery", Re ...

Retrieving Axios error codes within an interceptor

How can error codes like ERR_CONNECTION_REFUSED (indicating the API server is down) and ERR_INTERNET_DISCONNECTED (indicating the local network is down) be accessed when using response interceptors with axios in client-side JavaScript, React, etc.? While ...

AWS Lambda Error: Module not found - please check the file path '/var/task/index'

Node.js Alexa Task Problem Presently, I am working on creating a Node.js Alexa Skill using AWS Lambda. One of the functions I am struggling with involves fetching data from the OpenWeather API and storing it in a variable named weather. Below is the relev ...

Mastering the art of transforming a block of code nested within main(){} into a functional structure in the C programming language

Currently, I am developing a user-space driver that reads data from a HID device by sending and receiving reports. You can find my initial code at http://pastebin.com/ufbvziUR Edit Note: Based on the responses and comments, it appears that I will need to ...

Executing jQuery script on dynamically loaded content

My website utilizes AJAX requests to load pages dynamically. One specific page includes a marquee script that I would like to implement. Unfortunately, due to the dynamic loading of the page, the marquee script is not functioning as expected. I have come ...

The variable ReactFauxDOM has not been declared

Exploring the combination of D3 and React components. Utilizing OliverCaldwell's Faux-DOM element has led me to encounter a frustrating error message stating "ReactFauxDOM is not defined”. Despite following the npm install process correctly... It s ...

Encountered an error trying to access property 'history' of an undefined value while using react-router v4 and create-react-app

I encountered an issue with using Link to navigate, here's the breakdown of my code: Directory structure components ----App.js ----home ----Home index.js index.js import React from 'react'; import ReactDOM from 'react-dom'; ...

What is the best way to integrate an AJAX callback into the stop condition of a `do while` loop?

Take a look at the code snippet below: let count = 0; do { $.ajax({ type: "POST", url: someurl, dataType: 'xml', data: xmlString, success: function(xml) { count++; } } while(co ...

What is the best way to read a file or Stream synchronously in node.js?

Kindly refrain from lecturing me on asynchronous methods. Sometimes, I prefer to do things the straightforward way so I can swiftly move on to other tasks. Unfortunately, the code below is not functioning as expected. It closely resembles code that was po ...

What could be causing this empty Ajax ResponseText?

$("b_xml").onclick=function(){ new Ajax.Request("books.php", { method:"GET", parameters: {category:getCheckedRadio(document.getElementsByName("category"))}, onSuccess: showBooks_JSON, onFailure: ajaxF ...

Promise-based React Redux Login: An error occurred during login process

I'm currently working on my first React+Redux application and I'm still in the scaffolding phase. As a newcomer to React, I've encountered an issue with my simple login app. The AuthAction returns a Promise from the login(username, password) ...

Exploring Angular 2's ngFor Directive with JSON Data

Recently diving into Angular2, I've been trying to extract data from a JSON file. While I have successfully retrieved the file using a REST client, stored it in a local variable within a component, and accessed certain properties of that variable, I&a ...

Setting an Alias for AVA Tests: A Step-by-Step Guide

I need to set up global aliases in my project without using Webpack or Babel. Currently, I am testing with AVA. The npm package module-alias allows me to define aliases in my package.json file. However, when I try to create a basic example following the d ...

Disregard the sorting of rows in the MUI Datagrid

Any advice on excluding the "TOTAL" row from sorting in MUI library? onSortModelChange={(test, neww) => { neww.api.state.sorting.sortedRows = [14881337, 2, 3] neww.api.setState({...neww.api.state}) } } Review ...

PHP: Extracting values from an associative array using its numeric key position

I'm dealing with an associative array that, when var dumped, looks like this: Array ( [tumblr] => Array ( [type] => tumblr [url] => http://tumblr.com/ ) [twitter] => Array ( ...

Safari having trouble auto-playing Vimeo iframe embed

Update 6/26/23: Seems like a mysterious change occurred, as now the Vimeo video on project pages is playing automatically for me in Safari without any specific reason. It's working fine on Chrome too. Not sure if Vimeo made an update or if it's r ...

Regular expression that prohibits the acceptance of numbers with leading zeros

Below is the directive I am using to ensure that the input consists purely of numbers from 0-9. import { Directive, HostListener, ElementRef } from "@angular/core"; @Directive({ selector: "[numbersOnly]", }) export class OnlynumberDi ...

Generating an order prior to payment being made by the customer

When a user selects a product and clicks the pay button, they are redirected to Stripe where a new order is created. However, if the user changes their mind and cancels the payment during the Stripe checkout process, the order has already been created. How ...

Retrieve the values from an array nested within another array, potentially in a serialized format

Can anyone help me figure out how to extract variables from an array within another array? Do I still need to unserialize it? All I need are the variables "Auswahl01" and "Auswahl02." Here's the array: array(1) { [0]=> array(1) { [0]=> ...

Click on a button to send the React Router path as a parameter in

I've got a React form with a submission button like this: <Link className="btn btn-secondary btn-width-200 search-submit" to={{pathname: '/booking/search', query: this.state.filters}}> Search </Link> Within the ...