I've done FizzBuzz several times but never had this problem. Perhaps, it is something fundamental about for-loops that I don't understand. For some reason, the code below runs 10x longer than it should (well, than I think it should). If the user enters 20, it runs to 200. I fixed the problem by setting i = 0; i < num and then printing i+1 to my div, but I still don't understand why the original code does not work as expected. And while I'm at it, I might as well admit that I still can't set up JSFiddle properly. http://jsfiddle.net/nngrey/hA4pg/ (This does not run at all.) So any thoughts on that would also be appreciated. Thanks!
<head>
<title>Fizz Buzz</title>
<script>
function fizzbuzz(){
var num = prompt("Please enter a number between 1 and 100: ");
for(var i=1; i<num+1; i++){
if (i%3===0 && i%5===0){
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>Fizz Buzz</p>";
}else if (i%3===0){
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>Fizz</p>";
}else if (i%5===0){
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>Buzz</p>";
}else{
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>"+i+"</p>";
}
}
}
</script>
</head>
<body onLoad = "fizzbuzz()">
<div id = "div1">
<h1>Fizz Buzz</h1>
</div>
</body>
In your code, prompt() returns a string. Javascript will evaluate this line:
for(var i=1; i<num+1; i++){
with num as a string. i.e num+1 becomes "20"+"1" (note the quotes) which is "201". the comparison is then evaluated numerically, so your loop runs ten times linger than it should.
In your revised version i < num is evaluated numerically, so the loop runs for the correct period.
You can force num to be a number like this:
var num = Number(prompt("Please enter a number between 1 and 100: "));
num is now a number, so 20 + 1 = 21 (note - no quotes) and both versions of your loop should operate correctly
You need to do:
var num = parseInt(prompt("Please enter a number between 1 and 100: "), 0);
prompt returns a string, so if you enter 20, num+1 is the string "201", not the number 21.
here num is a string you have to use parseInt to convert it to int
for(var i=1; i<parseInt(num)+1; i++){
}
The prompt() returns a string.
Simple use +prompt() instead. That should make it a number. Updated code demo.
Related
I currently have this small script that outputs a value after each iteration of a while loop:
var i = 0;
var number = "";
while (i < 10) {
number += console.log(i);
i++;
}
Which creates this output:
0
1
2
3
4
5
6
7
8
9
However, I am testing some API calls and using the while loop in JavaScript to see if I can send values consistently, so my values are coming from the script below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
i++;
}
I do not need console.log() because I do not need the output in the terminal. My issue is when looking at the output on the receiving end when using the API, it looks something like this:
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
The API calls are in the while loop as well, I did not include them because I feel this is a JavaScript syntax related issue. So what will happen is that the while loop begins, number is iterated, that value is sent to a website using an API call, and the the while loop begins again. Something like the code below:
var i = 0;
var number = "";
while (i < 10) {
number += (i);
API_Send(number)
i++;
}
What can I do to so that the output of each iteration is its own separate variable similar to the output using console.log(), so first iteration is 0, second iteration is 1, and so on.
I feel this is something that would be necessary when outputting values to be used by a function. So perhaps it is best to create a function that has a while loop outputting integer values?
The problem is that you have declared number as string, don't do that just assign 0 to number variable.
Because of string variable javascript is concatenating the numbers.
Change as following:
var i = 0;
var number = 0;
while (i < 10) {
number += (i);
console.log(number)
i++;
}
Greetings Stack Overflow!
First off, this is my first question!
I am trying to solve the selfDividingNumbers algorithm and I ran into this interesting problem. This function is supposed to take a range of numbers to check if they are self dividing.
Self Dividing example:
128 is a self-dividing number because
128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
My attempt with Javascript.
/*
selfDividingNumbers( 1, 22 );
*/
var selfDividingNumbers = function(left, right) {
var output = [];
while(left <= right){
// convert number into an array of strings, size 1
var leftString = left.toString().split();
// initialize digit iterator
var currentDigit = leftString[0];
for(var i = 0; i < leftString.length; i++){
currentDigit = parseInt(leftString[i])
console.log( left % currentDigit );
}
// increment lower bound
left++;
}
return output
};
When comparing the current lower bound to the current digit of the lower bound, left % currentDigit it always produces zero! I figure this is probably a type error but I am unsure of why and would love for someone to point out why!
Would also like to see any other ideas to avoid this problem!
I figured this was a good chance to get a better handle on Javascript considering I am clueless as to why my program is producing this output. Any help would be appreciated! :)
Thanks Stack Overflow!
Calling split() isn't buying you anything. Remove it and you'll get the results you expect. You still have to write the code to populate output though.
The answer by #Joseph may fix your current code, but I think there is a potentially easier way to go about doing this. Consider the following script:
var start = 128;
var num = start;
var sd = true;
while (num > 0) {
var last = num % 10;
if (start % last != 0) {
sd = false;
break;
}
num = Math.floor(num / 10);
}
if (sd) {
print("Is self dividing");
}
else {
print("Is NOT self dividing");
}
Demo
To test each digit in the number for its ability to cleanly divide the original number, you can simply use a loop. In each iteration, check num % 10 to get the current digit, and then divide the number by ten. If we never see a digit which can not divide evenly, then the number is not self dividing, otherwise it is.
So the string split method takes the string and returns an array of string parts. The method expects a parameter, however, the dividing element. If no dividing element is provided, the method will return only one part, the string itself. In your case, what you probably intended was to split the string into individual characters, which would mean the divider would be the empty string:
var leftString = left.toString().split('');
Since you are already familiar with console.log, note that you could also use it to debug your program. If you are confused about the output of left % currentDigit, one thing you could try is logging the variables just before the call,
console.log(typeof left, left, typeof currentDigit, currentDigit)
which might give you ideas about where to look next.
I am still new to Javascript and I need help on how to display all even numbers in a single alert box. When I run the code, it only displays "21".
function myFunction() {
var i;
for (i = 2; i <= 20; i++) {
if (i % 2 == 0);
}
alert(i);
}
<h2>Even numbers from two to twenty</h2>
<button onclick="myFunction()">Display</button>
The value of i changes everytime the code in the loop is run.
By the time your code gets to the alert() function, the value of i is equal to the last uneven number you encountered.
A way of solving this is by adding all the uneven numbers to an array and then alerting the value of this array.
Like this:
<h2>Even numbers from two to twenty</h2>
<button onclick="myFunction()">Display</button>
<script>
function myFunction(){
var i;
uneven = [];
for (i=2;i<=20;i++){
if(i%2!=0){
uneven.push(i);
}
}
alert(uneven);
}
</script>
Every time the loop encounters a number that's uneven, it is added to an array. In the end the array will be a list of uneven numbers.
If you put this list in the alert() function, you'll get all the uneven numbers.
The modulus operator % also checks the remainder after a division. If the remainder after a division by 2 is 0, the number is even. Therefore you should add i to the uneven numbers when i%2 != 0. So when it's not even.
Your syntax is wrong. You have alert(i); after for loop is ended. So once forloop is finished i = 21.
so change it to
for (i=2;i<=20;i++)
{
if(i%2==0) {
alert(i);
}
}
}
<h2>Even numbers from two to twenty</h2>
<button onclick="myFunction()">Display</button>
<script>
function myFunction()
{
var i;
var evenNo=[];
for (i=2;i<=20;i++)
{
if(i%2==0)
evenNo.push(i);
}
alert(evenNo.join(", "));
}
</script>
This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 7 years ago.
So, in writing a program - in javascript - that sums numbers from 1 to N (number given by user), I have written a working program, but I am still confused as to why one proposed solution that I wrote works, and the other doesn't.
This version works:
function spitback(){
var theNum = prompt("Give me a number");
var onwards = 0;
for(i = 0; i <= theNum; i++){
onwards += i;
}
console.log(onwards);
}
spitback();
This one does not:
function spitback(){
var theNum = prompt("Give me a number");
var onwards = theNum;
for(i = 0; i <= theNum; i++){
onwards += i;
}
console.log(onwards);
}
spitback();
Why doesn't the second one work? If I initially set var onwards as theNum (inputted by a user) and then have the function add onwards to the iterations of 'i' up until the counter reaches theNum, I will see a concatenation between theNum and all the iterations of i next to it, like it is a string. In my mind, setting a variable to the same value and then having that value change to add the counter's iteration should work! Why doesn't it work? Please share.
This is because prompt returns a string, not a number. And when you use "+" operation on a string, you get concatenation, not integer increment. Javascript will not magically convert your string into integer even if it looks like it.
Lets assume you can never know what string will be passed to the browser, any combination of any characters of any length and I want to limit this to lets say.. 50 chars.
This is what I have at the moment:
<script type="text/javascript">
var x = "Hello this sentance was created in the browser!"
for(i=0; i<x.length; i++){
if(i == 50){
}
}
</script>
Eventually x will be something like:
var x = $('#textBit').html();
How will I remove everything in the array (string) after position 50, will I need a new for loop kinda like this (it may be wrong just thinking it up) pseudo code:
loop remainder string{
do until end of array{
remove item
}
}
Or is there a better way of doing it? Thanks.
use the string.substring(indexA[, indexB]) method:
Returns a subset of a string between one index and another, or through
the end of the string.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring
No:
if (x.length <= 50)
return x;
else
return x.substring(0, 50);
Just use substr() (MDN docu). This will return the substring meeting you criteria, e.g., beginning at the start and having at most 50 characters:
var x = "Hello this sentance was created in the browser!"
var shortString = x.substr( 0, 50 );