Elements that have been added to an Array and now making a

Hello, I have a question about working with arrays. I did search for answers before posting this but couldn't find a solution.

My goal is to create a simple code where a prompt asks for names until no name is entered. However, when I try to access the array at the end, it only shows 'true' instead of the actual names.

I am new to working with arrays and have tried various methods without success in getting the correct names. Can anyone provide some guidance on this issue?

var enterNames = new Array();
var i;

while(i = prompt("Please enter a name", "") != "")
{
    enterNames.push(i);
}
document.write(enterNames);

Thank you in advance for any help you can offer.

Best regards, Jack

Answer №1

Understanding the logic of operator precedence is key: when evaluating your while condition, the != is processed first to produce a boolean value before the assignment with the = operator assigns it to i.

To address this, you can use parentheses to group the operations as needed:

while((i = prompt("Please enter a name", "")) != "")

In the given example:

var enterNames = [];
var i;

while((i = prompt("Please enter a name", "")) != "") {
    enterNames.push(i);
}
document.write(enterNames);

(It's worth noting that assigning values within a loop condition may be discouraged by some developers, but it does function in this scenario. Additionally, using [] is generally preferred over new Array() for creating an empty array. Lastly, utilizing document.write() is typically not recommended.)

Answer №2

let namesEntered = []; //using let instead of var
function askForName(){
  let name = prompt("Please enter a name", "");
  if(name === ""){
    askForName();
    return;
  }
  namesEntered.push(name);
}
askForName();
console.log(namesEntered);

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

Deciphering the mechanics of collection referencing in mongoose

Today, I am delving into the world of using references in mongoose for the first time. I am trying to figure out how to save a template with a user ID. Do we need to retrieve the createdBy value from the client, or can it be inserted into the templateSchem ...

Tips for importing a Multimaterial .dae file in three.js?

I am facing an issue while trying to load a model with multiple materials. I want to access the array of materials but my current approach is not working as expected. loader.load('./dae/tenis.DAE', function ( collada){ dae = collada.scene; ...

Having trouble retrieving Bengali-language data from the server using jQuery AJAX

I am facing an issue where I am unable to fetch data in Bengali language from the server using ajax. Strangely, the data retrieved from the server is getting replaced by some unknown characters. However, if I directly retrieve the data without using ajax, ...

Copy the rows of a two-dimensional array in order to incorporate all dates falling within the specified start and end date range of each row

Within my code, I am working with an array named $exhibitions: Array ( [0] => Array ( [exhibition_title] => Picasso [venue_name] => Gallery 1 [room_name] => Room 4 [start_date] => 2 ...

How can state be shared between sibling components in React?

As someone who is relatively new to React, I am seeking guidance on the proper method of passing states between components. While I did come across a similar inquiry on Stack Overflow, I would appreciate if someone could provide a specific solution for my ...

Repeated elements found in Array

What is the most effective method to prevent duplicate keys when performing typecasting in PHP? For example: //Credits @bwoebi $obj = (object)array(1,2,3); $obj->{1} = "Duplicate key 1"; $obj->{2} = "Duplicate key 2"; $obj->{3} = "Duplicate key ...

Creating a canvas in Javascript that allows users to drag and drop elements within set boundaries

In my latest project, I have implemented a feature that allows me to move a canvas by changing its X and Y positions. The code snippet below demonstrates how this functionality works: https://jsfiddle.net/rrmwub4h/1/ var canvas = document.getElementById(" ...

Verify with PropTypes whether the props object is a valid JSON structure

How can I use the prop-types package to validate whether a placeholderProp, which is of type string, contains valid JSON? In the parent Component: <Component placeholderProp={'{"a":1}} /> Component.js import React from "react" import PropTyp ...

Creating a TypeScript record with the help of the keyof operator and the typeof keyword

I have an object set up with my enum-like times of day and I am attempting to create the correct type for a record based on these entries. export const TIMEOFDAY = { FirstLight: 'First Light', Morning: 'Morning', Antemeridie ...

Organizing a schedule of dates while also incorporating them into the existing collection of items

I am faced with a task involving a list of articles that display dates in the format "YYYY-MM-DD". My goal is to extract the month and day from these strings and convert them into a new format, such as "Oct 11", for example. To achieve this, I have implem ...

There seems to be an issue with the rendering of face normals in Three

I am in the process of creating my own model format and attempting to generate custom geometry. Although I can successfully import the geometry, the face normals do not render even after being added to the geometry. Below is the input file: # Coordinates ...

Manipulating data with Angular's array object

I am having an issue with posting an object array. I anticipate the post to be in JSON format like this: {"campaign":"ben", "slots":[ { "base_image": "base64 code here" } ] } However, when I attempt to post ...

Dealing with repeated parameters in a URLHow can you handle duplicate

My Ajax select input dynamically changes the URL without refreshing the page. However, I have encountered an issue where repeated parameters stack in the URL when the select input is changed multiple times: [domain]/find.php?cat=1#pricemin=10&pricem ...

Directing JSON POST Request Data to View/Controller in a Node.js Application

Currently, I am working on a project hosted on a local server at http://localhost:3000/. This server receives a post request from another server in the following manner: return requestLib.post({ url: 'http://localhost:3000/test', timeout ...

Error: OBJLoader is not defined in Three.js

I've been trying to learn Three.js by following various tutorials, but I keep encountering an error message that says Uncaught ReferenceError: OBJLoader is not defined when I attempt to use my own .obj file. I've tried different approaches to fix ...

The Array Result of a WordPress WP_Query

I need assistance with modifying my WordPress homepage to display only 2 blog posts, each with a different floating element - one on the left and one on the right. In native PHP, I can easily fetch results as an array and print them using $result[0] and $r ...

Stop options from being hidden in a select dropdown using HTML

Can I keep the options visible when a user selects an item in the 'select' dropdown? I want to add more options to the 'select' when the user clicks on the 'op2' item, without closing the list of options. <select> <o ...

deleting a row from a table once XmlHttpRequest is finished

My situation involves an HTML table containing multiple rows, each of which includes an id attribute and a delete button within a cell. To handle the deletion process, I have implemented an ajax call attached to the delete button using the following code: ...

Unable to assign a value to a property within a JavaScript object

I'm attempting to configure settings for a JavaScript object (my assumption is that it's not a plain JS Object, but possibly an instance of a specific class, though I haven't been able to identify the class). https://i.sstatic.net/xsUiJ.png ...

Problem with full-page navigation sliding in and fading in and out

Upon the user's click on <a href="#slide-nav" class="slide-nav-trigger">, a full-page navigation smoothly slides into view. This animation is triggered by CSS and uses jQuery for event delegation. The Dilemma Instead of abruptly turning on and ...