Been browsing SO for some time since I picked up a programming course, and have found it to be an awesome community and great place for knowledge.
Currently I'm stuck with a JavaScript function that I'm trying to clean up.
I need to have names input into an array, and then when I run a 'start' function, it would display the amount of names as a number, and then show each name on a new line.
I've managed to get it working, however there is a ',' character at the start of each line. I've tried various ways to get around it (using replace and split + join) but had no luck so far.
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
};
document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName + "<br>");
return custName;}
}
The reason is most likely because you are trying to display arrName which is an Array with this code: document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
Here's what I'd suggest:
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
}
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;}
}
Since there is no need for the WHILE Loop, You can skip it like so:
var arrName = [];
var custName;
function start(){
var totalName = arrName.length;
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;
}
}
An array when console logged or inserted to DOM directly will be represented as item1,item2,item3,item4
So simply, arrName.join("<br />")
Also, your while loop can be simply replaced by
totalName = arrName.length;
count = arrName.length
Related
I am trying to the splice method but it is not working properly want to delete one user but it is deleting 2.
Also want to add the binary search button
this is the requirement for binary search
Replace the sequential access algorithm to operate on the arrays with a binary search algorithm.
To implement this, the array’s data must be sorted. You may refer to an online example available at Array.prototype.sort() to learn about sorting data in arrays.
function Display_Athlete() {
var text = "<hr/>";
for (let i = 0; i < athlete_name.length; i++) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
document.getElementById("message").innerHTML = text;
}
//Created function to remove the user
function Remove_Athlete() {
var person = prompt("Enter the name to remove the Athlete");
for (let i = 0; i < athlete_name.length; i++) {
athlete_name.splice(person - 1, 1);
athlete_height.splice(person - 1, 1);
alert(" Athlete_name " + athlete_name + " Athlete_height " + athlete_height + " is removed ");
}
}
//Create the function to find the user
function Find_Athlete() {
var person = prompt("Enter the name to Find the Athlete");
var text = "";
for (let i = 0; i < athlete_name.length; i++) {
if (athlete_name[i] == person) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
}
document.getElementById("message").innerHTML = text;
if (text == "")
alert(`${person} Invalid Athlete name`);
return "";
}
function Binary_Search(){
}
I have written a code that finds two strings and in return it should tell me if these two strings are existing:
function searchTwoString(data, str1, str2) {
var strX = str1 + " " + strValueX + "\r\n";
var strY = str2 + " " + strValueY;
var strValueX;
var strValueY;
for (var i = 0; i < data.length; i++) {
if (data[i] === str1) {
var strValueX = " exist";
continue;
} else if (data[i] === str2) {
var strValueY = " exist";
break;
}
}
return strX + strY;
}
Achieved result:
str1 undefined
str2 undefined
Expected result:
str1 exist
str2 exist
it tells me my strvalueX & strvalueY are undefined isn't it i have already gave the values in the if statement?
thanks to those who will help out
Here is an answer to your question with comment.
Hope you understand what I'm talking about.
function searchTwoString(data, str1, str2) {
var strX;// = str1 + " " + strValueX + "\r\n";
var strY;// = str2 + " " + strValueY;
var strValueX;
var strValueY;
for (var i = 0; i < data.length; i++) {
if (data[i] === str1) {
// var strValueX = " exist";
// do not define again
strValueX = " exist";
continue;
} else if (data[i] === str2) {
// var strValueY = " exist";
// do not define again
strValueY = " exist";
break;
}
}
// define the value here after strValueX and strValueY is set
strX = str1 + " " + strValueX + "\r\n";
strY = str2 + " " + strValueY;
return strX + strY;
}
The order of your statements is off. In lines 2 and 3, you are using strValueX and strValueY before they are defined. Lines 2 and 3 should be moved to before the return so that they will have the updated values.
I believe there is also a shadowing problem, as in the if statements you are creating new variables with the var keyword (e.g. var strValueX = " exist";). You will want to remove var from the if statements so that it updates the values of the outer variables.
I am trying to pass my results value from to projectYears() function to projectInvestment() function that will then write to the div tag. I am getting the error "result is not defined error". To me this makes sense. All the code is working as intended. Can someone please let me know how to achieve this.
function projectInvestment(nameId, investmentId, interestId, yearsId, amountId) {
var inputName = document.getElementById(nameId).value;
var inputInvestment = parseFloat(document.getElementById(investmentId).value);
var inputInterest = parseFloat(document.getElementById(interestId).value);
var inputYears = parseInt(document.getElementById(yearsId).value);
var inputAmount = parseFloat(document.getElementById(amountId).value);
projectYears(inputInvestment, inputInterest, inputYears);
var outputString = projectYears(result);
document.getElementById("outputDiv").innerHTML = outputString;
}
function projectYears(inInvest, inInterest, inYears) {
var interest = parseFloat(inInterest / 100);
var interestAmt = parseFloat(inInvest * interest);
var predictedInvest = parseFloat(inInvest + interestAmt);
var result = "<br /> Investment Schedule for <b>$" + inInvest.toFixed(2) +
" </b>at <b>" + inInterest + "% </b>annual interest for <b>" + inYears + "</b> years <br /><br />";
result += "<table border='1' align='center'><tr><th>Year</th><th>Amount</th>";
//for loop to loop through the years
for (var x = 1; x <= inYears; x++) {
result += "<tr><td>" + x + "</td><td>" + predictedInvest.toFixed(2) + "</td></tr>";
interestAmt = predictedInvest * interest;
predictedInvest = (predictedInvest + interestAmt);
}
result += "</table>";
return result;
//document.getElementById("outputDiv").innerHTML = result;
}
You are passing in a variable called result that isn't defined.
See this line in the projectInvestment function:
var outputString = projectYears(result);
It looks like, based on the function definition for projectYears, you should be passing in some of the variables you create above this line instead.
i.e.
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
var inputAmount = parseFloat(document.getElementById(amountId).value);
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
document.getElementById("outputDiv").innerHTML = outputString;
I have a problem here, basically I want my Dice game to display 3 lines.
The first line says what number of the die I got
The second line adds the number I got from the first die with the second die i rolled and so on.. (basically everytime i click the button).
The third line would just count how many times I rolled the dice.
My problem is that on my second line, im not sure how I can add up my current die roll with my previous one everytime I click the button.
var count=0;
function swap_pic()
{
var x = Math.floor(Math.random()*6)+1;
var pic = document.getElementById("dice");
var xx = x+x;
count++;
document.getElementById("result").innerHTML = "You got " + x;
document.getElementById("result").innerHTML += "<br>Your score is: " + xx;
document.getElementById("result").innerHTML += "<br>Number of tries = " + count;
if (count==5)
{
document.getElementById("result").innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>";
count = 0;
document.getElementById('button').setAttribute("style","visibility:hidden");
}
if (x==1)
{
pic.src = "images/die1.png";
}
else if (x==2)
{
pic.src = "images/die2.png";
}
else if (x==3)
{
pic.src = "images/die3.png";
}
else if (x==4)
{
pic.src = "images/die4.png";
}
else if (x==5)
{
pic.src = "images/die5.png";
}
else if (x==6)
{
pic.src = "images/die6.png";
}
}
Problem is this line
document.getElementById("result").innerHTML += "<br>Your score is: " + xx;
Thank you for the help guys!
Several concatenation of innerHTML should be avoided, as well as repeated else if when possible. Try this:
var count = 0;
var sum = 0;
function swap_pic() {
var x = Math.floor(Math.random() * 6) + 1;
var pic = document.getElementById("dice");
sum += x;
count++;
var html = "You got " + x;
html += "<br>Your score is: " + sum;
html += "<br>Number of tries = " + count;
if (count == 5) {
html += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>";
count = 0;
document.getElementById('button').setAttribute("style", "visibility:hidden");
}
document.getElementById("result").innerHTML = html;
pic.src = "images/die" + x +".png";
}
Try this on for size
//create these as global variables
var totalScore;
var rollCount;
var lastRoll;
var image;
var text;
var button;
function reload(){
totalScore = 0;
rollCount = 0;
lastRoll = 0;
image = document.getElementById('dice'); //store image element
text = document.getElementById('result'); //store result element
button = document.getElementById('button'); //store button element
button.style.visibility = visible; //restore button visibility
}
function roll(){
lastRoll = Math.floor(Math.random()*6)+1; //generate random number
rollCount++; //increase our roll counter
totalScore+= lastRoll; //add new roll to score
image.src = "images/die" +lastRoll+ ".png"; //update dice image
text.innerHTML = "You got " // generate result string
+ lastRoll
+ "<br>Your score is: "
+ totalScore
+ "<br>Number of tries = "
+ rollCount;
if(rollCount >= 5){ //end game parameter!!
text.innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>"; //add game over text
button.style.visibility = 'hidden';//hide button
//reload(); //uncomment to reset game now?
}
}
window.onload = reload; //set up on page load
I have made a vowel counter in pure js but I cannot get the counters to work properly. and i cannot seem to find out where i am going wrong just need a little push or example to know how to fix this if that is ok. Can someone please help me thanks in advance.
This is my HTML:
<h1> Vowel Counter </h1>
Please enter text for your vowel count:
<br>
<textarea id="text" rows="10" style="width: 100%;"></textarea>
<br>
<button onclick="countVowels();">Count Vowels</button>
<p id="result"></p>
This is my Javascript:
function countVowels() {
var text = document.getElementById("text").value;
var arrayOfLetters = text.split("");
var arrayOfVowels = ("AEIOU");
// Set up our counters
var countA = 0;
var countE = 0;
var countI = 0;
var countO = 0;
var countU = 0;
// Output the results:
document.getElementById("result").innerHTML = "";
document.getElementById("result").innerHTML += "Total Letters: " + arrayOfLetters.length + "<br />";
document.getElementById("result").innerHTML += "A's: " + arrayOfVowels.length + countA + "<br />";
document.getElementById("result").innerHTML += "E's: " + arrayOfVowels.length +countE + "<br />";
document.getElementById("result").innerHTML += "I's: " + arrayOfVowels.length +countI + "<br />";
document.getElementById("result").innerHTML += "O's: " + arrayOfVowels.length +countO + "<br />";
document.getElementById("result").innerHTML += "U's: " + arrayOfVowels.length +countU + "<br />";
}
And a have attached my jsfiddle:
http://jsfiddle.net/Matt1990/3Ckw2/43/
I would recommend using regular expressions instead of loops and so many if conditions. The complexity and maintainability of the code is bad in the above solutions unless you consider regex as not being pure js.
var countA = text.match(/[Aa]/g).length;
This will give you direct count. For finding maxval, use basic sort algorithms to find the max and then assign a css style class to it. That is not a technical problem to solve.
How are you counting the vowels?
Right now it is showing 50 for each vowel count because arrayOfVowels.length = 5 and countA (for example), is simply 0. You aren't adding any numbers together, but you're adding 5 to the string 0 which results in "50".
You simply have no mechanism to count vowels, it's not that your "vowel counter" doesn't work. You set up everything correctly but fail to work through the text and systematically count the vowels. You can improve this code by automatically making the letters lower or upper case, so you don't have to use the or operator to check for both cases. I could've done that fast but I am just too lazy...
This vowel counter will work:
function countVowels() {
var text = document.getElementById("text").value;
var arrayOfLetters = text.split("");
var arrayOfVowels = ("AEIOU");
// Set up our counters
var countA = 0;
var countE = 0;
var countI = 0;
var countO = 0;
var countU = 0;
for(i=0; i < arrayOfLetters.length; i++) {
if (arrayOfLetters[i] == "A" || arrayOfLetters[i] == "a") {
countA ++;
}
if (arrayOfLetters[i] == "E" || arrayOfLetters[i] == "e") {
countE ++;
}
if (arrayOfLetters[i] == "I" || arrayOfLetters[i] == "i") {
countI ++;
}
if (arrayOfLetters[i] == "O" || arrayOfLetters[i] == "o") {
countO ++;
}
if (arrayOfLetters[i] == "U" || arrayOfLetters[i] == "u") {
countU ++;
}
}
// Output the results:
document.getElementById("result").innerHTML = "";
document.getElementById("result").innerHTML += "Total Letters: " + arrayOfLetters.length + "<br />";
document.getElementById("result").innerHTML += "A's: " + countA + "<br />";
document.getElementById("result").innerHTML += "E's: " + countE + "<br />";
document.getElementById("result").innerHTML += "I's: " + countI + "<br />";
document.getElementById("result").innerHTML += "O's: " + countO + "<br />";
document.getElementById("result").innerHTML += "U's: " + countU + "<br />";
}