See a screenshot of my returned data i did a console.log on which i need to do a for each on.
i have been trying things like this to no avail...?
for (var point in arrayLatLngPoints)
{
addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour);
}
Don't use for..in to loop an array, use normal for loop instead.
for (var i = 0; i < arrayLatLngPoints.length; i++)
{
var point = arrayLatLngPoints[i];
addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour);
}
Related
I am using NodeJS and Express and iterating over an array of strings, for example:
[ "1" , "+" , "B4", "*", "8"]
If the string contains a letter, the function should go off and call a GET method to retrieve a value from the Database. My code so far looks like this:
function processFormula(formula) {
console.log(formula)
var arr = formula.split(" ");
for (var i = 0; i < arr.length; i++) {
if (arr[i].match(/[a-z]/i)) {
/* fetch the value and store it in arr[i] */
}
return arr.toString();
}
My problem is that the method which goes off to fetch the value takes longer to execute than the processing thread, resulting in
undefined
cropping up a lot. I am struggling to understand where exactly I should be placing my callback to deal with this situation iteratively?
Any help is greatly appreciated!
That is tricky to coordinate. You could try using a HTTP request library like axios that uses promises. Then, you can use Promise.all to coordinate all the requests.
You can add another if inside the for and return until you at the last element:
for(var i = 0; i < arr.length; i++){
if (arr[i].match(/[a-z]/i)) {
/* fetch the value and store it in arr[i] */
}
if(i == arr.length-1){
return arr.toString();
}
}
And a suggestion, try using array.length outside for loops, because each loop you will be calculating the length of the array to check if condition is achieved, therefore going through array each time. (I didn't change that in my answer). Just do it before the loop and do var size = array.length
i wanna generate a 3x3 field. I want to do this with JS, it shall be a web application.
All fields shall inital with false. But it seems so that my code is not working correctly, but i don't find my fault. The goal is, that every spacesector is accessible.
Thats my idea:
// define size
var esize = generateSpace(3);
}
space[i] = false is replacing the array with a single boolean value false, not filling in all the entries in array you just created. You need another loop to initialize all the elements of the array.
function generateSpace(x) {
var space = [];
for (var i = 0; i < x; i++) {
space[i] = [];
for (var j = 0; j < x; j++) {
space[i][j] = false;
}
}
return space;
}
Also, your for() loop condition was wrong, as you weren't initializing the last element of space. It should have been i < space.length.
And when it's done, it needs to return the array that it created.
Since I got somewhat bored and felt like messing around, you can also initialize your dataset as shown below:
function generateSpace(x) {
return Array.apply(null, Array(x)).map(function() {
return Array.apply(null, Array(x)).map(function() {
return false;
});
});
}
The other functions work equally well, but here's a fairly simply looking one using ES6 that works for any square grid:
function generateSpace(x) {
return Array(x).fill(Array(x).fill(false));
}
Is there a good way to add a certain value to each element in an array in javascript? Essentially, this should be a better way of writing the following:
a = [1,2,3,4];
for (i = 0; i < a.length; i++) {
a[i] += 7;
}
Maybe using map (but not necessarily)?
Edit:
Or a more interesting example:
a = [{'x':1},{'x':2},{'x':3},{'x':4}];
for (i = 0; i < a.length; i++) {
a[i].x += 7;
}
You can use map to do it:
a = a.map(function(entry) {
return entry + 7;
});
I'm not seeing how it's "better" to create a new array rather than update the one you have.
You can also use forEach:
a.forEach(function(entry, index) {
a[index] += 7;
});
It's still a bunch of function calls (but that's not a problem), but you have the advantage (over a for loop) of not having to declare the indexing variable, and you're modifying the existing array rather than replacing it.
Edit: Your "most interesting" example says even more that map is not really the best choice.
a.forEach(function(entry) {
entry.x += 7;
});
Yes, you can use .map but it will not modify the array in-place, so you must assign the result to a:
a = a.map(function(x) { return x+7 });
How can I get the value BrandName in this image using javascript loop.
UPDATED: Since data variable you use to display the response is already a CartObject then use:
for (var i = 0, len = data.CartLists.length; i < len; i++) {
console.log( data.CartLists[i].Item.BrandName );
}
An alternative to the one VisioN said is the following:
for (var CartItemId in CartObject.CartLists) {
Console.log(CartObject.CartLists[CartItemId].Item.BrandName);
}
However, If you would attach an Prototype to the JSON object, you could obtain an Object in the for-loop instead of an Integer (Number).
for (var CartItem in CartObject.CarLists) {
Console.log(CartItem.Item.BrandName);
}
Note that if you are going to make everything right, you should insert the following in the for-loop:
if (CartObject.CarLists.hasOwnProperty(CartItem)) {
Console.log(CartItem.Item.BrandName);
}
This example will work, but as seen in the comments below. The use of it is not what it is designed for. The For-In loop is designed to loop over Object properties, not Array items.
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.