i have a below function through which i am trying to append something. it internally calls another function which does the append function..
function something()
for(var i=0; i <= obj.result.length; i++) {
EDIT
obj = objEval.result[i].uniquename;
prop = objEval.result[i].prop;
count = objEval.result[i].count;
// count is 21 in my case. below function is called..
if (count > 0){
callAdd(obj,prop);
}
}
}
actual function that does the appending
function callAdd(obj,prop){
// obj exists in DOM.. checked via $(obj).length -- greater than 0
$(obj).append(prop);
}
issue here is, even if the append function is in for loop.. only the first element is being sent to the callAdd function.. as below:
i have 4 obj, props:
obj=45183371 and prop=6
obj=560488951 and prop=12
obj=616516330 and prop=23
obj=915329019 and prop=5
but only the first pair (obj=45183371 and prop=6) is being sent to the callAdd function as params..
pls help..
something() generally needs to be added a param, other-wise how would it function? where would it build its loop? Global var? I dont see one
Try this.
Get all objs in an Array.
var objAry=new Array();
Get all props in an Array.
var propsAry=new Array();
Now
function something()
{
var propsAry=new Array();
var objAry=new Array();
objAry= //Your objs
propsAry=//Your props
for(var i=0; i <= objAry. length; i++)
{
if (count > 0)
{
callAdd(objAry[i], propsAry[i]);
}
}
}
You are changing the variable you're depending on (obj) to limit your loop control variable (i). When you re-assign obj inside the body of the loop:
obj = objEval.result[i].uniquename;
The looping condition:
i <= obj.result.length
Will be false on the next iteration. Inside the body of the loop, create a new variable instead of assigning something new to obj.
Alternatively (or additionally), cache the number of iterations you want in a variable instead:
var len = obj.result.length;
for (var i = 0; i <= len; i++) {
// Do whatever you want to obj.
}
You dont have count defined so use i:
if (i > 0){
callAdd(obj,prop);
};
Related
How to get the loop values outside the loop below example only prints the last value, For example if i wanted to print the loop results.
var result;
for (var i=0; i < 10; i++) {
result = i;
}
console.log(result);
Now how can i get the iterated values of the loop which are (1 to 10) in the console, because now i will only print the last value which is 10.
Put the log statement inside the loop where you set the value.
var result;
for (var i=0; i < 10; i++) {
result = i;
console.log(result);
}
If you only want one output statement, you can concatenate your results before logging:
var result = "";
for (var i=0; i < 10; i++) {
result += i + " ";
}
console.log(result);
This will output 0 1 2 3 4 5 6 7 8 9 10
If you really want to log outside of the loop, wich is quite unnecessary in my opinion, may use an array? :
var result=[];
for (var i=0; i < 10; i++) {
result.push(i);
}
console.log(...result);
http://jsbin.com/gogeluhavi/edit?console
If you want result make to log magically, you may uses setters and a Proxy, so called Observables.
Enter result=10 into this console, ive implemented a Observable for you: http://jsbin.com/xacujabuwo/edit?console ; You could also paste your for loop...
The Above answears are correct but I would like to clear it up for you so you understand it too.
In your original code you have declared the variable "result" outside the loop, then at each iteration a value is assigned to your variable. So that first time around "result" = 0 , second loop and the "result" = 1 and so on.
When the the for loop is finished it reads the next line which is your console.log() statment with the variable "result". The last time the variable "result" was modified was inside the for loop at the 10th iteration and thats where you let it equal to the iterator,therefore the value of iterator is 11.
In order to display something at every iteration, the console.log() must be placed inside the loop. Check below example
var result;
for (var i=0; i < 10; i++) {
result = i;
console.log(result); // prints at every iteration
}
Since you didnt add jQuery tag I used only javascript.
Add a input hidden tag
<input id="idOfInput" style="visibility:hidden" type="text">
Set the desired value to the input
for (var i=0; i < 10; i++) {
result = i;
document.getElementById('idOfInput').value = result;
document.getElementById('idOfInput').change(); //note change() is to trigger the event
}
Add change event listener and get the value set in loop
var input = document.getElementById('idOfInput');
input.addEventListener('input', function()
{
console.log('input changed to: ', input.value); //you get the value here
});
hope it helps
var result=[];
for (var i=0; i <= 10; i++) {
result.push(i);
}
console.log("Result =>", result);
I've written the functions below as part of a much larger application for processing FASTA formatted files via a web interface. For some reason it decided to run into infinity when call upon my baseCounts() function from within makePretty(). It might be worth noting that both functions are encapsulated by the same parent function.
The function baseCounts() returns valid data in the form of a 100+ long array, console.log confirms that it is not to blame so the problem has to be with makePretty().
Any help is welcome.
function baseCount(records){
// Count instances of Bases in array
var basecounts = Array();
for (i=0; i < records.length; i++){
var record = records[i];
console.log(record);
var count = [record.match(/A/g), record.match(/T/g), record.match(/C/g), record.match(/G/g)];
var basecount = Array();
for (i=0; i < count.length; i++){
basecount.push(count[i].length);
}
// return array of occurance
basecounts.push(basecount);
}
}
function makePretty(fasta){
// Make FASTA more human friendly
var data = Array();
var basecounts = Array();
var bases = Array();
console.log(fasta.length);
// Generate base array
for (i=1; i < fasta.length; i++){
bases.push(fasta[i][2])
}
basecounts = baseCount(bases); // RUNS INTO INFINITY
for (i=0; i < fasta.length; i++){
var record = Array();
record.push(i); // Add protein number
record.push(fasta[i][0]); // Add NC_#
record.push(fasta[i][1]); // Add base index
_record = fasta[i][2];
var l_record = _fasta.length; // Protein length
//var basecount = baseCount(_record);
var cg_content;
}
}
Your nested loops are using the same variable i, and clobbering each other's state.
for (i=0; i < records.length; i++){
...
for (i=0; i < count.length; i++){
...
}
Use distinct variables, say i and j or better yet pick meaningful names.
Also you should declare the variables (var i) to ensure they're local to the function.
Finally, use ++i, not i++. The former means "increment i" while the latter means "i, and oh by the way increment it". They both increment i, but the latter one returns the old value, which is a special language feature to use in special cases.
You're reseting your variable counter in your inner loop (i).
To avoid this, and future problems like it as well as hoisting issues, I would suggest using the newer functions such as forEach or map. You can also clean up your code this way:
function baseCountFunc(records){
// Count instances of Bases in array
var basecount = [];
records.forEach(function(record) {
var count = [record.match(/A/g), record.match(/T/g), record.match(/C/g), record.match(/G/g)];
count.forEach(function(countElement) {
basecount.push(countElement.length);
});
basecounts.push(basecount);
});
}
Also, I noticed you named your function the same name as your variables, you should avoid that as well.
Here is a simplified version of something I'm trying to run:
for ( winDoorNo = 0; winDoorNo < aWinDoorSetSpec.no_of_winDoors; winDoorNo ++ ) {
(function (winDoorNo, self) {
self.tangentVectors_azimuth = [];
self.tangentVectors_polar = [];
self.tangentVectors_azimuth[winDoorNo] = tangentPlane.tangentVector_azimuth;
self.tangentVectors_polar[winDoorNo] = tangentPlane.tangentVector_polar;
})(winDoorNo, this);
}
but I'm finding that the self.tangentVectors_azimuth array only contains a value on the last value that the for loop index variable had. I found this post describing a similar problem and I implemented the suggested solution which is to use a closure. However this does not work for me. After the for loop has executed, the value of this.tangentVectors_azimuth is still:
[undefined, undefined, Object { x=0.01999999996662183, y=0.01599999957331022, z=0, more...}]
You are creating new arrays for each iteration in the loop, so each time you will throw away the previous result.
Create the arrays outside the loop:
this.tangentVectors_azimuth = [];
this.tangentVectors_polar = [];
for (winDoorNo = 0; winDoorNo < aWinDoorSetSpec.no_of_winDoors; winDoorNo++) {
this.tangentVectors_azimuth[winDoorNo] = tangentPlane.tangentVector_azimuth;
this.tangentVectors_polar[winDoorNo] = tangentPlane.tangentVector_polar;
}
I need to Loop in JQuery from 0 to variable-value(dynamically entered by user).How can i achieve this?
Now i am doing it by using simple For loop like this.
for( i=1; i<=fetch; i++) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Thanks.
You could loop an empty array:
$.each(new Array(fetch), function(i) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
});
If you do this alot you can even fake-patch jQuery.each to take numbers:
(function($) {
var _each = $.each;
$.each = function() {
var args = $.makeArray(arguments);
if ( args.length == 2 && typeof args[0] == 'number') {
return _each.call(this, new Array(args[0]), args[1]);
}
return _each.call(this, args);
};
}(jQuery));
$.each(fetch, function(i) {
// loop
});
jQuery.each does have some great features, like the different return values inside the callback. But for a simple loop I find it much more convenient (and less overhead) to do something like:
while(fetch--) {
// loop
}
To loop between two values you should use a regular Javascript loop. The jQuery each methods are used when looping through a collection of elements or an array.
To loop from zero, you should initialise the loop variable to zero, not one. To loop from zero to the specified value, you use the <= for the comparison, but to loop from zero and the number of items as specified (i.e. from 0 to value-1), you use the < operator.
for (i = 0; i < fetch; i++) {
$('body').append($('<input/>', { type: 'text' }));
}
You mean Javascript loop.
From W3Schools:
for (var variable = startvalue; variable < endvalue; variable = variable + increment)
{
//code to be executed
}
To get the value from user and run the code you can use the following prompt.
var x=prompt("Enter the value",0);
for(i=0;i<x;i++)
{
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Hope this helps.
Thanks
If you want it the full jQuery way then use that new plugin jQuery-timing. It provides inline-loops in your jQuery line:
$('body').repeat().append('<input>').until(fetch);
Nice, eh?
Here is my code:
var divarray = document.getElementById("yui-main").getElementsByTagName("div");
var articleHTML;
var absHTML;
var keyHTML;
var bodyHTML = [];
for( var i in divarray) {
if(divarray[i].className == "articleBody"){
articleHTML = divarray[i];
for( var j in articleHTML ){
bodyHTML[i] = '';
if(articleHTML[j].className == "issueMiniFeature"){continue;}
if(articleHTML[j].className == "abstract"){absHTML = articleHTML[i]; continue;}
if(articleHTML[j].className == "journalKeywords"){keyHTML = articleHTML[i]; continue;}
bodyHTML[i] = articleHTML[i];
}
break;
}
i++;
}
The error I am getting is:
SyntaxError: Unexpected token var
I am using Google Chrome
The javascript for...in doesn't do what you would expect (which is enumerate through eleemnts in an array.
for...in in javascript will enumerate through the key/value pairs (or public variables) that make up the object (which isn't what you want).
You need to use a good, old fashioned for loop.
You can add this to your script:
Array.prototype.foreach = function (callback) {
for (var i=0; i < this.length; i++) {
callback(this[i]);
}
}
Then you simply do this:
myarray.foreach(function (currentItem) {
/*...do whatever with the currentItem...*/
});
I think you mistaking JavaScript for the functionality of PHP. JavaScript does not have foreach loops. JavaScript has for in, which is what you are incorrectly using and normal for loops. Use a standard for loop when dealing with arrays. You will need to use a for in loop with object literals because the index is not the simplicity of an incrementing positive integer.
In JavaScript a for loop has 3 parts in its argument separated by a semicolon as follows:
* start position of incrementor (optional if the variable is previous defined with 0 or a positive integer)
* end position of incrementor
* method of incrementation
In the following examples arrayName is value I made up for the name of an array:
for (; a < arrayName.length; a += 1) {
for (a = x + 1; a < arrayName.length + 3; a += 2) {
The for in loop argument has two required parts and a third part to prevent errors using an if condition:
* The value of an index to search for
* The name of the container in which to search
* The third part is an if condition
The following example will return the value supplied to the "book" index of the objectName object literal. objectName is a name I made for an example object literal:
for ("book" in objectName) {
if (objectName.hasProperty("book")) {
Why not use a traditional for loop instead? You're not really using an associative array here ...
That's not the right way to iterate over a collection.
You want a standard for loop, not a for..in loop
for( var i = 0, l = divarray.length; i < l; i++ ) {
There's something else, you then proceed to try to iterate over each element
for( var j in articleHTML ){
articleHTML at this point holds a reference to a single HTML node - not a collection or array of any sort.