javascript function in a for loop not causing crashing browser - javascript

I'm new at coding and am trying to figure out why this doesn't work. the function works fine I'm assuming there is a fundamental flaw in the sumArray function that is not processing
// SET UP FUNCTIONS FOR LATER USE
// sumArray - takes all values within an array and adds them
var sumArray = function(x){
var sum = 0;
for(i=0;i<x.length;i++) {
sum += parseInt(x[i]);
};
return sum;
};
// create an array and use sumArray function inside of a loop.
// This works
var arrayTest = new Array(1,2,3,4,5,6,7,8,9,10);
document.write (sumArray(arrayTest);
// This crashes the browser
for(i=0;i<10;i++){
document.write("<br/>" + sumArray(arrayTest) + "<br/>");
};
Thanks in advance for any insight.

You need to declare "i" with var:
for(var i=0;i<10;i++){
in both loops. If you don't do that, there's just one global "i" clobbered by both loops.

Just before the second loop, you're missing a ).
document.write (sumArray(arrayTest) ); // <-- right here
Additionally, be very careful with document.write. If it runs while the document is loading, you'll probably be alright. Be sure you don't use it after the doc has loaded.

Related

reference json numeric key with variable in javascript

How to loop through this data: (I have no control over format)
{"rowCount":3,"1":{"K":"2009","V":"Some Data"},"2":{"K":"2010","V":"More Data"}}
Above is a console.log(results) and results is a string
var r = JSON.parse(results);
var t;
for(var i=1;i<=r.rowCount;i++) {
t=r[i].V;
tableData.push(
{title:t, year:'2009', hasChild:true, color: '#000'}
);
}
Error: TypeError: 'undefined' is not an object (evaluating 'r[i].V')
I cannot get it to evaluate the variable i. What am I doing wrong?
Thanks
UPDATE
The incoming data had a bad rowcount causing the error. The accepted answer however is correct... just user error on my part not catching the bad incoming data. Had I put a console.log inside the loop I would have realized the error was actually happening after two successful loops. oops
I assume r.rowCount should be j.rowCount.
Ideally you should also initialise the i variable if you haven't already (i.e. with the var keyword).
(I've also moved the var t declaration outside the loop, to make it clear that it's the same t throughout and you're just changing its value. You shouldn't redeclare it with var each time – although I doubt this affects the output.)
var j = {"rowCount":2,"1":{"K":"name","V":"john"},"2":{"K":"name","V":"sue"}};
var t;
for (var i = 1; i <= j.rowCount; i++) {
t = j[i].V;
console.log(t);
}
Working demo – JSFiddle

javascript function won't loop

Here is a piece of a javascript practice problem that I am working on:
function combo(str){
var splitStr=str.split("");
for (var i=0; i<splitStr.length; i++){
return splitStr[i];
}
}
console.log(combo("dog"));
Why won't the loop return all three letters? It prints "d" and stops. If I take the loop out of the function, it works.
What am I doing wrong? Please explain.
return ends the invocation of the function, giving you back whatever is after that return
Your code structure looks like you wanted it to act like yield but ES5- does not support this so you can't use it (yet), and you would still have other problems (i.e. you'd be logging just the first generated result)
Instead, pass your console.log (bound to console) into a the loop;
function combo(str, callback){
var splitStr=str.split("");
for (var i=0; i<splitStr.length; i++){
callback(splitStr[i]);
}
}
combo('dog', console.log.bind(console));
With return you will end the function and come out of it with that data, next things wont be called
You can return an array instead like this.
function combo(str){
return splitStr=str.split("");
}
console.log(combo("dog"));
You are returning from inside the for loop and this ceases the function's execution. If you want to return each letter of the array, just return the split array itself:
function combo(str) {
return str.split("");
}
The behavior you seem to want is somehow achievable using generator function (function*).
function* combo(){
var splitStr = str.split("");
for (var i=0; i < splitStr.length; i++){
yield splitStr[i];
}
}
Then you'd invoke it like this:
var generator = combo("dog");
console.log(generator.next()) //d
console.log(generator.next()) //o
console.log(generator.next()) //g
Please note, however, that so far only few browser support this feature.
return stops the execution of the function. The rest of the loop is not happening.
'return' within the loop ends the loop and returns the first value, since it allowed the loop to run only once.
putting the 'return' statement outside of the scope {} of the loop will allow the loop to continue to run/repeat.

Is this JavaScript code wrong?

In this JavaScript lesson on Codecademy it is required to write a do/while loop, I have written this, and it passes
var getToDaChoppa = function(b){
var a = b;
do{
console.log("Dunno!");
} while (a < b);
};
getToDaChoppa(25);
But when looking closely at my code, I think that I may have done it completely wrong since a has no defined value?
Or since the variable of b is local inside the function, it does not affect the b argument which is passed a value of 25?
Many thanks in advance.
It simply does only one iteration, because when the do while loop starts, the condition is not satisfied because a and b are equals. So
var getToDaChoppa = function(b){
var a = b;
do{
console.log("Dunno!");
} while (a < b); //25 < 25, exit
};
getToDaChoppa(25);
If you want to try a do while loop try with some trick like
var getToDaChoppa = function(b){
var a = 10; //or whatever minor than b
do{
console.log("Dunno!");
a++; //when it reaches 25 or whatever value you set it breaks the loop
} while (a < b);
};
This is just an example to let you figure out how do while works
The code's fine, the logic's wrong. You are assigning a the value of b, so they'll be always equal.
You are assigning the value of b to a with the statement var a = b;
The loop will run once since you are using a do while loop.
The code is not wrong, it is designed to illustrate that the condition is evaluated after the first iteration of the loop.
http://jsfiddle.net/puleos/QXC9z/
Is this JavaScript code wrong?
depends on what problem you wanted to solve.
It looks pretty useless to me since the body of the loop will always be executed once.
while (a < b);will always return false because of var a = b; and a is not modified in the loop.
I think what you're after is:
var getToDaChoppa = function(b){
var a = 0;
do{
console.log("Dunno!");
a++;
} while (a < b);
};
As mentioned by other posters, if a = b the loop will only run once. This version should run the expected number of times (if that truly is what's expected).
Since the question says "Your loop should print a string of your choice to the editor one time", I think this is correct. Your code will print the string "Dunno!" exactly one time.
However the a and b variables and the do..while loop might as well not exist at all, they are only adding unnecessary complexity to the code which could be simplified to one line (the console.log() call).

how could I pass closure problems in order to increment a global var

I have a simple goal, I would like to increment a variable but I'm facing the closure problem. I've read why this s happening here How do JavaScript closures work?
But I can't find the solution to my problem :/
let's assume this part of code I took from the link.
function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num); //incrementation
}
num++;
return sayAlert;
}
I would like to increment num within the function and to keep the changes to num.
How could I do that ?
Here is the JsFiddle where I have my problem, I can't figure out how to increment my totalSize and keep it.
http://jsfiddle.net/knLbv/2/
I don't want a local variable that ends up with closure.
From your fiddle, I guess the problem is a mix of closure (totalSize should be outside of the loop) and query.exec being asynchronous (this one can be verified with some console.log).
What you seem to need is some kind of control flow, something like async.reduce
function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num++); //incrementation
}
return sayAlert;
}
var inscrese = say667();
so if you want to increase by one just call increase();
If all other solutions fail, then make num an array: var num = [666], then increment it's first element: num[0]++.

Incremental while loop becomes infinite

I'm trying to create a new folder with an ascending number on the end if a folder already exists, but I end up in an infinite loop
var i=1;
while (myFolder.exists == true) {
var myFolder = new Folder(wf+"/"+curFile+"_folder"+i)
i++;
};
Any help would be appreciated.
It looks like myFolder.exists is a method, not a property, so you have to call it:
while (myFolder.exists()) {
var myFolder = new Folder(wf + "/" + curFile + "_folder" + i);
i++;
};
Otherwise, you would be evaluating the method itself, which is indeed always true in a boolean context.
Note in passing that redefining myFolder inside the loop is probably not the problem here. Loops in Javascript share the same scope as the enclosing code, and the variable will be hoisted to the start of that scope. As jdwire says, it can be undefined initially, but then you would receive an error instead of triggering an infinite loop.

Categories