var setOfCats = {}; //an object
while (r = true) //testing to see if r is true
{
var i = 0;
setOfCats.i = prompt ("What's your cat's name?", ""); //index object elements
alert ("Congratulations! Your cat has been added to the directory.");
var r = confirm ("Would you like to add another cat?"); //if r is true, then the loop should continue. if false, the loop should end.
i++
}
However, the loop does not end. I've been pondering this problem, with futile attempts, for the last 30 minutes. Any ideas?
Your comment is incorrect.
r = true doesn't test whether r is true; it assigns r to become true.
You need to compare the variable using the === operator.
Or you can just write while(r), since r itself is already true.
while (r = true)
You're setting r to true each loop iteration. You want while (r == true), or just while (r).
For clarity, r and setOfCats should be set outside the while declaration:
var setOfCats = [];
var r = true;
while (r) {
setOfCats.push( prompt ("What's your cat's name?", "") );
alert ("Congratulations! Your cat has been added to the directory.");
r = confirm ("Would you like to add another cat?");
}
You are re-assigning the value of r to true upon each iteration of the while expression. Therefore, it will always override the value.
You should do the while test with:
while(r === true)
or more idiomatic:
while(r)
This should work:
var setOfCats = {}; //an object
var r = true;
while(r) //testing to see if r is true
{
var i = 0;
setOfCats.i = prompt ("What's your cat's name?", ""); //index object elements
alert ("Congratulations! Your cat has been added to the directory.");
r = confirm ("Would you like to add another cat?"); //if r is true, then the loop should continue. if false, the loop should end.
i++
}
Related
I'm a beginner trying to learn JS, I've got some basic knowledge.
I wrote a function to realize insertion sort on a given array (the array is passed on to the function as a parameter).
When I initialize the array and give it value, e.g,
sampleArray = [1,35,73,234,1,1,356];
and pass that to my function, it works perfectly.
however, if I try to pass on an array filled by user input - or an array that was merged out of two given arrays (my original assignment),
it doesn't work - no exceptions or errors, it just... doesn't sort as expected.
I've been racking my mind over this, maybe I don't know where to look?
function sortArray(arrT) {
for (let i = 1; i < arrT.length; i++){
var tempMax = arrT[i];
var j = i - 1;
while ((j >= 0) && (arrT[j] > tempMax)) {
console.log(arr1 + "\nj=" + j + " i=" + i);
arrT[j+1] = arrT[j];
j--;
}
arrT[j+1] = tempMax;
}
console.log("sorted array is (inside loop) :\n" +arrT);
return arrT;
}
for an array that was filled by a while loop of prompts such as
it's equal to the above sample array, the result is
1,1,1,234,35,356,73
for reference, though it's far from elegant, I'm using this to fill the array:
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
arr1[i]=prompt("enter");
}
As per my understanding.
The mistake is here
Original Code:
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
arr1[i]=prompt("enter");//do not use prompts while unnecessary. Just replace it with x;
}
Corrected One:
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
/*
you can also improve your code by applying few checks
if(!isNaN(x)) continue; // --- to skip when input value isn't a number
*/
arr1[i]=x;
}
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
arr1[i]=prompt("enter");
}
prompt actually returns a string, hence your input is an array of strings instead. You should use Number to ensure the provided value is numeric.
I would rewrite the above in this way:
// stores all the values.
var arr1 = [];
// Stores the current value.
var input;
do {
var _ = prompt("press x to finish, enter to continue"); // <-- not sure why you're doing that every time, I would suggest you to move it outside of the loop.
input = prompt("enter");
var n = Number(input);
if (!isNaN(n)) arr1.push(n); // <-- checks whether the provided value is actually numeric and a valid number. If it is, the value is added to the collection.
}
while (input !== 'x');
console.log(arr1);
I would suggest you to move the first prompt outside of the loop, but since you did it in your code, I suspect there is a reason for that, though I don't get it.
In any case, the above sample will check whether the value passed is valid; if it is, it push the item to the collection, otherwise it continues until 'x' is met.
So, I'm designing a code that will enable the user to create pseudo-custom operations that one can use under a special eval() function (as JavaScript is not an extendable language). My problem is that only the first variable created seems to register and be evaluated.
I am posting here a large snippet of the code.
var CMD = function(){
var objs = gAO() /* gets all of the objects */;
// testing for other instances of the CMD object.
this .bool = 0;
for(obj in objs) this .bool ^= !objs[obj]["_aqz39"] // boolean
if(this .bool){
// DEFINING VARS
this .objs = objs;
this["_aqz39"] = true;
this .ops = []; this .eqs = [];
}
}
{ /* init */
var cmd = new CMD();
}
// USER INPUT FOR CREATING 'NEW VARIABLES'
var Operator = function(op,input){
// SYNTAX: "<operator>","x <operator> y = <result, using 'x' and 'y'>"
// EXAMPLE: "#","x # y = 3 * x - y"
this .op = op;
this .eq = input.split("=")[1].trim();
}
// FUNCTION FOR ACTIVATING THE VARIABLE TO BE
// ...RECOGNIZED BY THE CMD's 'EVAL' FUNCTION
activate = function(ind){
cmd.ops.push(ind.op);
cmd.eqs.push(ind.eq);
}
CMD.prototype.eval = function(equ){
// DECLARING VARS
var t = cmd,oper,equation,x,y,i=0;
// LOOPS THROUGH ALL OF THE CHILDREN OF cmd.ops
while (i < t["ops"].length){
// CHECKS TO SEE IF THE INPUT CONTAINS THE SYMBOL
if(equ.search(oper) !== -1){
// the operator
oper = t["ops"][i];
// the equation
equation = t["eqs"][i];
// from the first index to the beginning of the operator
x = equ.slice(0,equ.search(oper)).trim(),
// from right after the operator to the end of the thing
y = equ.slice(equ.search(oper)+1,equ.length).trim();
/* INFORMATION LOGGING */
console.log({x:x,y:y,oper:oper,equation:equation,i:i,t:t,bool: equ.search(oper),len:t["ops"].length})
// RESULT
return eval(eval(equation));
}
// INCREMENTS 'i'
i++;
}
// ELSE
return false;
}
Testing #1
var hash = new Operator("#","x # y = 3 * x - y");
var dash = new Operator("q","x q y = y");
activate(dash);
activate(hash);
console.log(cmd.eval("3 q -2")); // RETURNS -2
console.log(cmd.eval("3 # -2")); // RETURNS NOTHING
Testing #2
var hash = new Operator("#","x # y = 3 * x - y");
var dash = new Operator("q","x q y = y");
activate(hash); // HASH IS CALLED FIRST THIS TIME
activate(dash);
console.log(cmd.eval("3 q -2")); // RETURNS NaN
console.log(cmd.eval("3 # -2")); // RETURNS 11
I've been troubleshooting this thing for about an hour, and I have no idea what's going wrong. Help is highly appreciated.
Here you are using the variable oper before you have assigned anything to it:
if(equ.search(oper) !== -1){
oper = t["ops"][i];
The undefined value will be converted into an empty regular expression, so it will always return a match, that's why the first operator works. In the next iteration the variable will be assigned the wrong operator.
Assign the operator to it before using it to look for the operator:
oper = t["ops"][i];
if(equ.search(oper) !== -1){
I've just started learning coding on code academy and I'm really new to this.
I'm trying to make this program ask the user for values which it adds to an array from which it calculates the sample standard deviation.
// This array stores the values needed
var figures;
getStandardDeviation = function() {
// I need at least two figures for a standard deviation
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
// Checks whether user wishes to add more values to the array
var confirm = prompt("Would you like to add another? (Y or N)").toUpperCase();
// I can't figure out why the following if statement is not executed
// It checks whether the user wishes to add more values and adds them to the array
// If not it breaks the for loop
if (confirm === "Y"){
for ( i = 0; i === 100; i++){
figures[i + 2] = prompt("Enter a number:");
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
// The rest of the code works fine from here onwards
var sumx = 0;
var n = figures.length;
for(var i = 0 ; i < n ; i++) {
sumx += figures[i];
}
console.log("Sum = " + sumx);
var sumXsq = 0;
for( i = 0 ; i < n ; i++) {
sumXsq += (figures[i] * figures[i]);
}
console.log("Sum x squared = " + sumXsq);
var sxx = (sumXsq - (sumx * sumx)/n);
console.log("Sxx = " + sxx);
var v = sxx/(n - 1);
console.log("Variance = " + v);
var standardDev = Math.sqrt(v);
console.log("Standard Deviation = " + standardDev);
};
getStandardDeviation();
The program is supposed to ask me if I want to add more values to the array, then when I confirm, it gives me a prompt to add more values.
Currently, when I execute the program I input the numbers 56 and 67. The code then asks me if I wish to add more values, I then confirm this. Instead of letting me add more values it ignores this and calculates the standard deviation with the first two values (56 and 67).
The output is:
Sum = 05667
Sum x squared = 7625
Sxx = -16049819.5
Variance = -16049819.5
Standard Deviation = NaN
for ( i = 0; i === 100; i++){[...]} means
Set i to 0
If it's not true that i === 100 (that is: if i is not 100), end the loop
Do whatever I put inside the {} braces, once
Do i++
Back to 2
As the initial value for i is 0 and not 100, the code inside the loop is never executed. If you want it to go from 0 to 99, it should be for ( i = 0; i < 100; i++).
You don't actually need a for loop, though. A while loop would be better. A loop like while (true){[...]} would run until it hit a break statement. As you wouldn't have the i in that case, you could use figures.push(parseFloat(prompt("Enter a number:"))) instead (you should use parseFloat, as per what Vincent Hogendoorn said) . push adds a new value at the end of an array, so it's exactly what you need. Something like:
if (confirm === "Y"){
while (true){
figures.push(parseFloat(prompt("Enter a number:")));
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
You could also change it so it doesn't ask if you want to stop if you don't have at least two values. That way you would be able to leave out that first part:
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
indeed your figures variable isn't defined as an array, like #James Donnely says.
Keep in mind you also fill in strings, so if you want to add up values you have to convert them to values.
you can use something like parseFloat for this.
if you don't use it, you sum up strings. 3+4 will be 34 instead of 7.
Your figures variable isn't defined as an array. Because of this figure[1] = prompt(...) never gets hit and a TypeError is thrown on var n = figures.length;.
Change:
var figures;
To:
var figures = [];
JSFiddle demo.
You can then replace the for loop you're using after if (confirm === "Y") with a recursive function:
// Push a user input number into the figures array
figures.push(prompt("Enter a number:"));
// Function to add a new number and ask if we want to add more
function addNewNumber() {
// Push a new user input number into the figures array
figures.push(prompt("Enter a number:"));
// Ask if the user wants to add another number
if (confirm("Do you want to add another number?"))
// If they do, call this function again
addNewNumber();
}
// Trigger the function for the first time
addNewNumber();
JSFiddle demo with recursion.
function StandardDeviation(numbersArr) {
//--CALCULATE AVAREGE--
var total = 0;
for(var key in numbersArr)
total += numbersArr[key];
var meanVal = total / numbersArr.length;
//--CALCULATE AVAREGE--
//--CALCULATE STANDARD DEVIATION--
var SDprep = 0;
for(var key in numbersArr)
SDprep += Math.pow((parseFloat(numbersArr[key]) - meanVal),2);
var SDresult = Math.sqrt(SDprep/numbersArr.length);
//--CALCULATE STANDARD DEVIATION--
alert(SDresult);
}
var numbersArr = [10, 11, 12, 13, 14];
StandardDeviation(numbersArr);
I am fairly new to Javascript and have been picking it up pretty quickly in the past few days, after staring at my code for hours and trying to figure out why it wasn't working the way I intended i figured i would post it here.
Anyways, so my question is how do I display the WHOLE content of an array after comma splitting it. My code is below. My code is only printing out the last number set that I input at the prompt.
Help would be highly appreciated.
var gradeinfo = new Object(); {
coursecode = new Array;
grade = new Array;
};
var changer = function (y) {
finalgradeinfo = new Array;
finalgradeinfo = y;
function newresults() {
var i = 0;
finalgradeinfo[i] = y;
i + 1;
}
return finalgradeinfo;
}
do {
var entry = prompt("Enter a course code and grade seperated by a comma");
if (entry != null && entry != "") {
var counter;
var entryvalid = new Array;
entryvalid = entry.split(",");
changer(entryvalid);
x = true;
} else {
x = false;
}
} while (x != false);
console.log(finalgradeinfo);
My function needs to include closure so if it looks entirely wrong i apologize in advance.
Help from this post
Split creates an array already. So, if you enter 1,2,3, you get an array like this when you split it: ["1", "2", "3"]. In your for loop, you are getting the characters from the original input, not your array. In order to add them, you need to change the input to numbers since they are considered strings. So your for loop should look like this:
for (i=0; i<3; i++)
{
entryArray[i] = parseFloat(entryArray[i]);
}
overwriting the strings with the digits.
In changer() you're destroying and recreating the array after each input. I suggest moving the array declaration into the global scope so that you can just push elements to it in the changer() function:
Fiddle
var finalgradeinfo = [];
var changer = function (y) {
finalgradeinfo.push(y);
}
do {
var entry = prompt("Enter a course code and grade seperated by a comma");
if (entry != null && entry != "") {
var counter;
var entryvalid = entry.split(",");
changer(entryvalid);
x = true;
} else {
x = false;
}
} while (x != false);
console.log(finalgradeinfo);
Notes:
Declaring arrays as [] is preferred to new Array
Not sure if you're aware but the newresults() function and gradeinfo object aren't doing anything
Also, the counter doesn't do anything, and the x boolean is unnecessary because it's basically just checking for prompt input. Here is my approach and fiddle.
var finalgradeinfo = { // declare finalgradeinfo in the global scope
coursecode: [],
grade: [] }
, entry = '';
do {
entry = prompt('Enter a course code and grade seperated by a comma') || ''; // will set entry to '' if user hits cancel
if (entry == '') continue; // break out of iteration if string is empty
var entryvalid = entry.split(",");
finalgradeinfo.coursecode.push(entryvalid[0]);
finalgradeinfo.grade.push(entryvalid[1]);
} while(entry !== '');
console.log(finalgradeinfo);
My webpage crashes when I run this:
function replace()
{
var str = document.getElementById('feeds');
var cont = str.innerHTML;
curstring = "twitter: ";
while (cont.indexOf(curstring))
{
replaced = cont.replace(curstring,"TWIMG ");
str.innerHTML = replaced;
}
}
Yes, when curstring is in cont. In your while loop cont won't be changed, so cont.indexOf(curstring) will always be true.
Probably, yes.
Your cont.indexOf() test should test for >= 0, since on not-found that function returns -1, which evaluates true and will cause the loop to go around again.
It'll currently only terminate if cont starts with curstring.
Per other answers, you also need to overwrite cont inside the loop too.
function replace() {
var curstring = "twitter: ";
var str = document.getElementById('feeds');
var cont = str.innerHTML;
var old = cont;
// NB: indexOf() returns -1 on failure, so you
// must compare against that,
while (cont.indexOf(curstring) >= 0) {
cont = cont.replace(curstring, "TWIMG ");
}
// taken outside the loop so we don't modify the DOM
// over and over if the match is repeated - only update
// the DOM if the string got changed
if (cont !== old) {
str.innerHTML = cont;
}
}
Yes there is. You never reassign cont. Perhaps try this?
function replace()
{
var str = document.getElementById('feeds');
var cont = str.innerHTML;
curstring = "twitter: ";
while (cont.indexOf(curstring) != -1)
{
replaced = cont.replace(curstring,"TWIMG ");
str.innerHTML = replaced;
cont = str.innerHTML;
}
}
Yes cont never changes in the loop so if cont.indexOf(curstring) is true it will be true forever and your program goes into an infinite loop.