Is there a way to verify if the array numbers between "pages" and "endingPages" are the same? If they match, return true; otherwise, return false

After entering a number when prompted, the current page does not go through the function as expected. Instead, it simply changes to whatever number I input when prompted.

INSTRUCTIONS : Create a while loop with the condition while(currentPage !== null)

Within this loop, follow these steps:

  1. Determine if the currentPage is an ending. To ensure clean code, create a function for this task.

Your function should have a single parameter, currentPage.

Use a loop to compare the current page with the numbers in endingPages.

If the matching page is found within endingPages, return true; otherwise, return false.

Utilize this function in the while loop to confirm if the current page marks an ending.

  1. If the page is indeed an ending, display that page and exit the game. Since the while loop stops when currentPage is null, set the current page to null for the loop to end in the next iteration.

Hint: It would be visually appealing to print something like "GAME OVER" or "The End" at this point... CODE

console.log(pages[0]);
    
    let endingPages = [4, 9, 13, 17, 19, 20];
    let currentPage = 0;
    let pages = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    // Your Code Here.
    
    currentPage = prompt("Enter page:")
    ending(currentPage);
    
    function ending (currentPage){
        
        while(currentPage !== null) {
            for(let i = 0; i <= endingPages.length ; i++ ){
                currentPage = endingPages[i]
            if (endingPages[i] === pages.length){
                return true
            }else{
                return false
            } 
            }
        }
    }

Answer №1

It seems that there is some confusion here. The currentPage variable never changes because in Javascript, function parameters are passed by value.

In your code, I don't see any attempt to display the currentPage after the user has been prompted and the function has been called.

Regardless, your function should still return the desired outcome, and you can simply test whether it returns true or false by using

if (ending(currentPage)) { console.log("Game Over!"); }

There are 2 obvious flaws in the provided code:

  1. The while loop inside the function is unnecessary as currentPage should never be null
  2. You can refer to the first answer on this page for an easier way to generate a consecutive range of numbers

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

Having trouble accessing the true "valid" property within a function utilizing ref and VeeValidate

In my code, I am using a <ValidationObserver ref="observer"> with several ValidationProviders inside. In order to access the "valid" property of a specific field named "Unit" in the method getUnit(), I currently use this.$refs.observer.fields["Unit"] ...

JavaScript can be used to deactivate the onclick attribute

Is there a way to deactivate one onclick event once the other has been activated? Both divs are initially hidden in the CSS. I'm new to programming, so any help is appreciated. Markup <a id="leftbutton" href="#" onclick="showDiv(this.id); return ...

AngularJS ng-click incompatibility causing non-functioning popover content

I've gone through all the posts regarding this issue, but unfortunately, none of them proved to be helpful. It seems that the jsfiddle and plunker links provided are no longer functioning as expected. My objective is quite simple - I want to place a ...

Bring Component into Vue if necessary

I have multiple menu types and would like to determine which type of menu to use by configuring it in .env.local. For example: VUE_APP_MENU_TYPE=2 Here is the code snippet from my javascript file: let menu = false; if (process.env.VUE_APP_MENU_TYPE === &q ...

Delete a div when a button is clicked through JavaScript

I'm having an issue with a form I created that duplicates itself - I can't seem to get the 'x' button to remove the corresponding div as needed. I have placed both buttons outside of the div like this: <button type="button" id="cro ...

Totaling all possible arrangements of row data

I'm currently facing an issue in MATLAB that I believe could be effectively resolved using recursion. However, I'm curious to know if there is a more elegant solution, possibly involving vectorized operations or built-in functions. Here's t ...

Guide to utilizing a script variable within a Kendo DataSource

i am working on a project that involves a dropdown and tree view functionality with drag and drop feature. @Html.DropDownListFor(model => model.xyz, Model.xyzlist, new { id = "dropdownid" }) my current task is to trigger a controller action method when ...

Loop through an array of JSON data using jQuery

While some may find this topic basic, I am struggling to iterate through a JSON object using jQuery and access the webpage name of each producer. Any assistance would be greatly appreciated. Below is my code for reference: { "producers": [ { ...

populating the frame buffer with a square

I am struggling to generate an ASCII art square using an unsigned character array and display it on the screen. Here is the code snippet I have so far: #include <stdio.h> #define W 80 #define H 23 static int clear(unsigned char *p, int lim) { ...

The slow loading time of the website can be attributed to the excessive loading time of over 30 seconds due

My website, , is experiencing slow loading times due to a file named "json.gdn/gpl" which is causing it to take over 30 seconds to load completely. Unfortunately, I am not familiar with how to resolve this issue. I discovered this problem while using . If ...

Using an associative array in a PHP function to perform conditional checks

I'm currently working on a mini-game that involves displaying cards based on randomly selected suits and numbers. Here's the code snippet: <?php $suite['heart'] = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); $suite['spa ...

Unable to include a fresh entry into an array (the value associated with a key) within a Mongoose schema

In my mongoose schema named users, there is a field called likes. Whenever a user likes another user's post, the userId of the liker is added to the likes array. router.put("/:id/like", async (req, res) => { try { const post = await Post.f ...

"Whenever an action is dispatched in Redux, the bindActionCreators method is involved

After spending 20 hours testing, I am still unable to figure out where I went wrong. Everything works perfectly when I use a store redux dispatch, but now I want to use actions with bindActionCreators. This is my action: import {bindActionCreators} from ...

What could be causing the server to not successfully receive the ajax request?

I need to conduct integration tests on a website that routes all requests through a proxy: var express = require("express"), http = require("http"), port = (process.env.PORT || 8001), server = module.exports = express(), httpProxy = requir ...

Create unique error messages using Vue validators

Two fields named text and email are included in my template. Below is the structure of the template: HTML <!DOCTYPE html> <html> <head> <title>Vue - Validations</title> <script src="Libraries/vue/vue.min.js&qu ...

How come React.js is not displaying images from local URLs?

In my React application, there is a form where users can submit an image file. To store the path of the submitted image locally for browser access, I utilized URL.createObjectURL to generate a URL for the file. Here is the code snippet: handleImageChange(e ...

Resolving problems with Modal Pop-ups

I have a Modal that I am trying to open with the code below. The modal opens fine and adds open to the parent class. However, when I click 'close', it does not close and does not add close to the class either. Can anyone shed light on why this ...

MATLAB issue: Unable to generate symbolic variables using an array loop

Having a specific cell array: MatrixF = {3x1 cell} {3x1 cell} MatrixF{1} ans = 'f1' 'f2 ' 'f3 ' MatrixF{2} ans = 'x1' 'x2 ' 'x3 ' The goal is to convert each item in the MatrixF arr ...

How can I completely alter the content of aaData in jquery.dataTables?

Looking to completely change the content of a datatable purely from a javascript perspective, without relying on Ajax calls. I've attempted using the following script: oTable.fnClearTable(); oTable.fnAddData(R); oTable.fnAdjustColumnSizin ...

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...