Printing each value of an array on a separate line Javascript - javascript

I have a program that involves Javascript to allow for interaction with a webpage. It's a baseball site so what I am doing is prompting the user to enter a month. The user can enter a number, like 6 for June, or the name of the month itself and the program will display all the games they are playing that month.
The way I did this was to create an array and store it with the game information. So the month of July would look something like this:
if(month == 7) // July
{
var gamesPlayed = ["7/1/16: Team1 # Team2", "7/3/16: Team2 # Team 4",
"7/4/16: Team3 # Team2" , ... ,etc, ...];
}
In my main function (the one that executes when I push the Submit button), I want to print the array.
var schedule = getSchedule(July);
for(var i = 0; i < schedule.length; i++)
{
document.getElementById("result").innerHTML = schedule[i] + "<br />";
}
For some reason this does not work. All it does it print the very last value in the array and not the whole thing. How come it is not printing the whole array? I tried to do document.write(schedule[i] + "<br />"); and that didn't do what I wanted. It printed it, but it printed it on a page by itself to where I couldn't time in a new month or go back to a homepage, etc. Is there a way to get this to print all the elements and not just the last one?

You can use .join() to combine the array into one string, and separate each entry by <br>:
document.getElementById("result").innerHTML =
schedule.join("<br>");
There's no need for the self-closing / in <br>. More important, there's no need for the for loop. That code above will do the whole thing.
If you want a <br> after the last entry, just add it:
document.getElementById("result").innerHTML =
schedule.join("<br>") + "<br>";

While Pointy's answer is correct it does not explain why your code is not working. I'll try and explain:
The error is in this for loop and how you are using innerHTML.
for(var i = 0; i < schedule.length; i++)
{
document.getElementById("result").innerHTML = schedule[i] + "<br />";
}
Basically, on each iteration of the loop you are resetting the HTML of the result element instead of appending to it. The following small change is all that would have been needed.
for(var i = 0; i < schedule.length; i++)
{
document.getElementById("result").innerHTML += schedule[i] + "<br />";
}
However, Pointy's answer is more efficient for sure.

Related

Is there any way to print multiple lines in JS alert box using loop?

Hey guys I want to ask if there is any way to write multiple lines in one JS alert box using for loop?
I WANT TO HAVE OUTPUT LIKE THIS WITH ONE STRING VARIABLE AND ANY LOOP,
HOW CAN I HAVE OUTPUT LIKE THIS WITH ABOVE MENTIONED REQUIREMENTS?
Use \n
alert("String 1\nString 2");
var p = '';
for (var i = 1; i < 5; i++) {
p+= "string " + i + '\n'
}
alert(p)

Making a custom function in Google Sheets, the code works outside of sheets but not in sheets

So I'm writing a custom function for Google sheets which is supposed to take a single row or cells, produce a 1 dimensional array and use that data to create a URL. This is basically so I can help my friends track the prices of an item in a video game.
I have ran the code in a javascript environment outside of Google Sheets and everything acted as expected. But when I put the code in the script editor, it runs with unexpected behavior. The range of cells will always be 1 row by 13 columns but some of the columns may be void so the script is supposed to truncate the array of values so that there are no empty indexes. Then it is supposed to insert a "." between each value as it is concatenated into a string to produce the final URL. For some reason it does not remove any values and the "." are ","s when the URL is created in the cell.
Here is the code:
function STONKLINK(prices, premrkt) {
var webLink = "https://turnipprophet.io?prices=";
var priceLink = "";
for (i = (prices.length - 1); prices[i] == 0; i--){
prices.pop();
}
for (i = 0; i < prices.length; i++) {
priceLink = (priceLink + prices[i] + ".")
}
priceLink = priceLink.substring(0, priceLink.length - 1);
if (premrkt == "N/A") {
webLink = webLink + priceLink;
} else if (premrkt == "Fluctuating") {
webLink = webLink + priceLink + "&pattern=0";
} else if (premrkt == "Small Spike") {
webLink = webLink + priceLink + "&pattern=3";
} else if (premrkt == "Large Spike") {
webLink = webLink + priceLink + "&pattern=1";
} else if (premrkt == "Decreasing") {
webLink = webLink + priceLink + "&pattern=2";
}
return webLink;
}
Any help is very much appreciated. Thank you so much.
EDIT: While I still do not understand why this is happening, and I would like to understand, I have added a simple work around. By adding this line of code
webLink = webLink.replace(/,/g, ".");
before the return, all the commas will be replaced with dots. Still, any insight into the problem will be much appreciated. Thank you again.
When you store values in Spreadsheets, the values which have a , are considered to be strings whilst the ones which have a . will be considered to be numbers.
So for example, if you have these values stored in the B column:
If you log the typeof(val1) and typeof(val2) (where val1 and val2 are the values stored in B1 respectively B2), this is what you will get:
So the issue you were encountering is due to this fact. The values you have stored in your sheet are numbers and when you try to build the webLink string they are converted into strings - therefore, the . for a number becomes ,.
Reference
Date and Number Formats

NaN Issue - Why does identical code returns diffrent results?

I'm working on a script to match scrambled words to their unscrambled counterpart, and I'm running into a weird NaN problem. I have inserted comments below to guide you further in understand my problem in hopes that you can give me an explanation as to why this problem is occurring. Thank you for your time and help.
NOTE: Two chunks of code that are exactly the same (but with different variable names) act differently. The latter works, but the former does not.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<body>
<form id="words">
<input type="hidden" value="html:),121212,21122112,asdfjkl;,hal9000,1234qwer,1q2w3e,test123,gambit,sports,hello!,willie,hashtags,oneway,whoknows,whyowhy,youwho,theone,sweet!,wo0Oot">
</form>
<br>
<li>leho!l</li>
<li>lilwie</li>
<li>thahsags</li>
<li>yaneow</li>
<li>kwosonhw</li>
<li>ohhywwy</li>
<li>oyuwoh</li>
<li>otheen</li>
<li>e!stwe</li>
<li>wtoO0o</li>
<script>
var words, scram, wordVals, scramVals, sum, i, I;
// Turn word list into an array.
words = [];
var words = document.getElementById("words").elements[0].value.split(",");
// Turn scrambled word list into an array.
scram = [];
for (var i = 0; i < 10; i++) {
scram.push(document.getElementsByTagName("li")[i].innerHTML);
};
// Next I iterate through each letter of each word (for the unscrambled words)
// and convert those letters into ASCII values - adding those together
// to get the total ASCII value of each word.
wordVals = [];
for (i = 0; i < words.length; i++) {
for (I = 0; I < words[i].length; I++) {
sum += words[i].charCodeAt(I);
// console.log(sum)
// Using console.log(sum), you see that the first 6 iterations return NaN.
// Each iteration (ASCII Value) for the first word in this loop
// words[0].charCodeAt(0, 1, 2, 3, 4, 5, 6), all returned NaN.
// But each word after the first iteration calculates the ASCII values
// like it's supposed to.
};
wordVals.push(parseInt(sum));
sum = 0;
console.log("Word[" + i + "]: " + words[i] + " - Value: " + wordVals[i]);
};
// typeof WordVals[0] = number
console.log("typeof wordVals[0]?: " + typeof(wordVals[0]));
// isInteger = false
console.log("isInteger wordVals[0]?: " + Number.isInteger(wordVals[0]));
// Here I am iterating through each letter of each word (for the scrambled words)
// and converting those letters into ASCII values - adding those values together
// to get the total ASCII value of each word.
// **This loop uses the same exact code as the one above (but with different variables)
// and it works correctly. Why is this?
scramVals = [];
for (i = 0; i < scram.length; i++) {
for (I = 0; I < scram[i].length; I++) {
sum += scram[i].charCodeAt(I);
};
scramVals.push(sum);
sum = 0;
console.log("Scram Word[" + i + "]: " + scram[i] + " - Value: " + scramVals[i]);
};
</script>
</body>
</html>
OUTPUT:
Word[0]: html:) - Value: NaN
Word[1]: 121212 - Value: 297
...rest of list omitted...
typeof wordVals[0]?: number
isInteger wordVals[0]?: false
Scram Word[0]: leho!l - Value: 565
Scram Word[1]: lilwie - Value: 646
...rest of list omitted...
I have tried using a different starting word in my word list but get the same NaN result.
I don't understand why the first block of code doesn't work when it is practically identical to the second block of code that does work!
Why am I getting a NaN on the ASCII values of each letter of the first word?
I'm a beginner, and realize that this is not the proper way to go about finding word matches. Regular Expressions is probably what I will try to end up using, but I need to figure this out so I can progress in the way that I learn.
Thank you. I use this site all the time because I love the no nonsense approach most of you take in addressing user requests. There are a lot of really smart people here donating their time and intelligence, and I really appreciate it.
I am also open to any tips you can give me to improve this code.
That is because undefined + Number is NaN. Initially, the sum variable is undefined. that is why the first value in the wordVals array is NaN.
Just set sum to 0 and it should work as expected, ex:
var words, scram, wordVals, scramVals, sum = 0, i, I;
For the first iteration you adding a number with undefined( ie sum). So it'l become NaN. make sum = 0; at the beginning

JavaScript Syllable Counter - Counting Per Line

Current
I’ve re-worked this syllable counter script to:
Get the value of textarea 1.
Count the number of syllables in textarea 1.
Display the results in textarea 2.
Update the count every time the value of textarea 1 is edited.
Act as a function (be able to run in multiple instances if wanted).
Example function of current code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
11
Current code
Here is the existing code as a JSFiddle.
Goal
I would like this script to:
Count the syllables of textarea 1 on a per line basis: presumably by splitting the textarea 1 value where there are line breaks e.g. .split('\n');.
Output the results, showing the total number of syllables counted per line.
Example function of desired code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
6
3
2
Problem
I’m quite stuck as to how to do this and would really appreciate any help or JSFiddle showing how to work with the existing code to achieve this.
Notes
For anyone who may be interested using in the syllable count function code itself: it’s not 100% accurate and fails on some words but gives a good general idea.
Try this and let me know if it's what you needed.
Callouts:
I created an array that spits the lines up stores them var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);.
Then loop through that array and do exactly what you did before, but on each array entry. Then store the results in tempArr, and display the tempArr results.
See Fiddle
function $count_how_many_syllables($input) {
$("[name=set_" + $input + "]").keyup(function () {
var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
var tempArr = [];
var $content;
var word;
var $syllable_count;
var $result;
for(var i = 0; i < arrayOfLines.length; i++){
$content = arrayOfLines[i];
word = $content;
word = word.toLowerCase();
if (word.length <= 3) {
word = 1;
}
if (word.length === 0) {
return 0;
}
word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '')
.replace(/^y/, '')
.match(/[aeiouy]{1,2}/g).length;
$syllable_count = word;
$result = $syllable_count;
tempArr.push($result);
}
$("[name=set_" + $input + "_syllable_count]").val(tempArr);
});
}
(function($) {
$count_how_many_syllables("a");
})(jQuery);

Repetition via for loop based on prompt output

So essentially what I'm trying to do is to figure out how to repeat a line x number of times based on a prompt's output.
i.e
<script>
var favnumber = Number(prompt("What is your favorite number?"))
for(var i=0;i<favnumber;i++){
System.out.println(name + "is bad at javascript");
}
</script>
any idea whats wrong?
JavaScript is not Java. So there is no function System.out.println() unless you define it.
To output you hav either to user the DOM, console or alert.
The later might look like this:
<script>
var favnumber = Number(prompt("What is your favorite number?"));
var name = 'Bob';
for(var i=0;i<favnumber;i++){
alert(name + " is bad at javascript");
}
</script>
Besides, try to get used to end every command with ;. Otherwise you run into many weird problems as a JavaScript beginner - and later as well.
JavaScript is not Java, so System.out.println doesn't have any special meaning. You have two options here: to use console.log(), or to use document.write().
I recommend you use console.log(), as it doesn't mess with the current page's HTML structure:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
console.log(name + ' is not Java');
}​
You'll need to open up your browser's JavaScript console to see those messages.
Using document.write() is a bit more cumbersome:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
document.write(name + ' is not Java');
document.write('<br />');
}​
Demo: http://jsfiddle.net/HC3Y2/

Categories

Resources