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++;
}
Related
I'm working on a problem where the task is to write a program which reconstructs each sentence out of a set of words and prints out the original sentences.
INPUT SAMPLE:
2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2
And the answer is:
However, it was not implemented until 1998 and 2000
So far I got to the point where I have combined the words and number hints together as a pair value in an object. The only problem I am running into is that there is actually a missing number hint, thus one of the words has an undefined value.
How can I fill in this value?
I have tried to use .HasOwnProperty() and for-looping through to see if one of the values equals to undefined, but neither has worked. Any input would be greatly appreciated!
function encyrption(str){
var string = str.split(";");
var words = string[0].split(" ");
var hints = string[1].split(" ");
var object = {};
for(var i = 0; i < words.length; i++){
if(object[hints[i]] === undefined){
/////???
}else
object[hints[i]] = words[i];
}
return object;
}
console.info(encyrption("2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2"));
I'd do something like that, just guessing that the missing hint is the last word, and that will always be the sixth position. If that's not the case I'd need more information about the problem test cases to solve it.
function encyrption(str){
var string = str.split(";");
var words = string[0].split(" ");
var hints = string[1].split(" ");
var hints_sorted = hints.concat().sort();
var missing_hint;
var object = {};
for(var i = 0; i < words.length; i++) {
if(hints_sorted[i] != i+1) {
missing_hint = (i+1).toString();
break;
}
}
hints.push(missing_hint);
for(var i = 0; i < words.length; i++){
object[hints[i]] = words[i];
}
return object;
}
console.info(encyrption("2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2"));
//Result: However, it was not implemented until 1998 and 2000
There you have a small explanation:
I created the hints_sorted array, which is a copy of the hints one, but sorted, so, in our example:
hints = ['9','8','3','4','1','5','7','2'];
hints_sorted = ['1','2','3','4','5','7','8','9'];
Then, inside the for, I'm comparing the value with the index + 1 (since the index inside the loop starts at zero):
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 5
7 -> 6
On the sixth element, we have 7 on our array and we are expecting 6, so it goes inside the if, we set 6 as our missing hint, and we break; the loop so it doesn't continue checking values.
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.
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.
I am learning Javascript and have run into an issue with the push method. When I use it within a loop it is making my array 33 items instead of just adding 3 to the list. Initial list is 1-10 items long, user defined. I initiated all the variables in the beginning of the script, and the variable items is only manipulated when the user initially tells me how long the array will be. From there it is basic exercises in array methods, and this is the one that is giving me problems. Following is the push part of the code. I appreciate any feedback and will put more code up if anyone feels it is necessary.
for (i = 0 ; i < 3 ; i++){
newfood = prompt("Please enter food " + (i + 1) + ".");
foods.push(newfood);
}
document.write("<ol>");
i = 0; //resetting variable i to 0
for (i = 0 ; i < items + 3 ; i++){
document.write("<li>" + foods[i] + "</li><br>");
}
document.write("</ol>");
Looks like you're running into string concatenation that's then treating the string as a numeric type. Convert what I assume is a string to an int:
for (i = 0 ; i < parseInt(items) + 3 ; i++) {
document.write("<li>" + foods[i] + "</li><br>");
}
I cam across the following function in javascript:
for (var number = 0; number <= 12; number = number + 2)
show(number);
The Output is the following
0
2
4
6
8
10
12
I expected it to be
2
4
6
8
10
12
14
Why is the "0" shown first and not "2" since the "number = number + 2"comes before the "show(number);"?
This because the order of the loop is like this:
Init number.
Check the condition.
Run the loop.
Increase number by 2.
and then 2-4 again until the condition is false, if so exits the loop.
the for loop translate to something like this:
var number = 0;
while (number <= 12)
{
show(number);
number = number + 2;
}
In general for loop always work like this:
for(Init Variable; Condition ; Changing Variable)
{
//Some Code
}
translates to:
Init Variable
while (Condition )
{
//Some Code
Changing Variable
}
think of it like this :
why did you write the yellow part ?
this is the seed part which you DO WANT TO BE CONSIDERED !
so it will start with its seed value and then - will be incremented ....
0 is the initial value for the number variable in the for loop of the function:
var number = 0;
The for loop is terminated when the number variable reaches 12:
number <= 12;
Here is some more information on for loops: http://www.w3schools.com/js/js_loop_for.asp