Mootools is adding unwanted function calls to JSON results - javascript

I have a function that gets a list of vehicles in an asp.net page
function GetVehicleCounts(totalVehicles, vehiclesInDepot, vehiclesInFilter, vehiclesInKnownLocations, vehiclesInUnknownLocations, vehiclesNotInDepot)
{
vehiclesInDepot.value = 0;
vehiclesInFilter.value = 0;
vehiclesInKnownLocations.value = 0;
vehiclesInUnknownLocations.value = 0;
vehiclesNotInDepot.value = 0;
var listofVehicles;
var count = 0;
for (var k in vehicles_dm) {
vehiclesInDepot.value++;
if (vehicles_dm[k].IsInFilter) {
vehiclesInFilter.value++;
}
if (vehicles_dm[k].CurrentFeatureType == 11) {
vehiclesInUnknownLocations.value++;
}
else {
vehiclesInKnownLocations.value++;
}
}
if (vehicles_dm != null) {
vehiclesNotInDepot.value = totalVehicles - vehicles_dm.length;
}
}
However, when I add Mootools to the page I run into the problem of Mootools adding all the function calls to the results. This ends up getting repeated for any function that is similar. Any ideas for correcting?
I don't have a choice about using Mootools and the existing page is done in jQuery.

I found the answer!
'for..in is not meant for array iteration. It iterates over all the properties of an object that are not built-in. Since MooTools has added more functions to Array prototype, they are now array properties as well. See this https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/For...in
Just use a basic for loop for array iteration.'
Javascript array iteration using for..in with MooTools included

Related

JS multidimensional array spacefield

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));
}

Loop and Functions

I'm having troubles gathering information about clicked eventListeners.
I have this loop which builds an array:
myButtonList = document.getElementsByTagName('a');
myAnchorList = [];
for (i=0; i < myButtonList.length;i++) {
if (myButtonList[i].getAttribute('class') == 'flagged') {
myAnchorList.push(myButtonList[i]);
}
}
For each <a> put into myAnchorList array, I also create another array storing other informations from the same tag (classe and other atrributes).
Here's where I'm struggling. I'm trying to set up an eventListener to send me back those information when those <a> are being clicked. But somehow, the fact that I create a function (for the eventListener) within a loop breaks everything.
for (i=0; i < myAnchorList.length; i++) {
myAnchorList[i].addEventListener("click", function(i){
console.log(alpha+' - '+beta[i]+" - "+charlie[i]);
});
}
My values will either be undefined or some other values which will be the same for each buttons I clicked. alpha is working well as it doesn't depend on any iteration of the loop, but not the others.
Can anybody see what I'm doing wrong here?
for (var i = 0; i < myAnchorList.length; i++) {
(function (i) { //Passes i to your function
myAnchorList[i].addEventListener("click", function () {
console.log(alpha+' - '+beta[i]+" - "+charlie[i]);
});
})(i);
}
The variable "i" in closure that you created in the loop will always retrieve the last value(myAnchorList.length - 1). You shouldn't create closure in a loop, and you can use a "factory" method to create closure instead.

Creating an array and storing it in sessionStorage with JavaScript?

I'm doing an assignment that requires us to add objects to a fake cart array from a fake database array, then go to a cart page that displays everything in the "cart." Now, that's all well and good, but for some reason I can't get more than one object to show up in the fakeCart array.
I'm fairly certain the issue is in this function, because everything displays properly otherwise in every way.
So, it turns out I posted code that I was tinkering with. I've since updated it to the almost-working one.
function addToCart(e) {
'use strict';
var fakeCart = [];
for (var i = 0; i < fakeDatabase.length; i++) {
if (fakeDatabase[i].id == e.currentTarget.id) {
fakeCart.push(fakeDatabase[i]);
}
}
sessionStorage.fakeCart = JSON.stringify(fakeCart);
}
Essentially, I can get the code to make a single object go from one array (database) to the other (cart), but whenever I try to add one back in it just replaces the last one.
The code overwrites any existing value of sessionStorage.fakeCart, so there will never be more than one element in the serialized array. You can fix that by reading the value from sessionStorage instead of creating a new list each time.
function addToCart(e, productNum) {
'use strict';
// change this
var fakeCart = JSON.parse(sessionStorage.fakeCart) || [];
for (var i = 0; i < fakeDatabase.length; i++) {
if (fakeDatabase[i].id == e.currentTarget.id) {
// and this
fakeCart.push(fakeDatabase[i]);
}
}
sessionStorage.fakeCart = JSON.stringify(fakeCart);
}
I think :
Instead of
fakeCart[i].push(fakeDatabase[i]);
you require this
fakeCart.splice(i, 0, fakeDatabase[i]);

Can't call public method while looping over object array

I'm starting to play around a bit with OOP in JavaScript and I have an array of simple objects that I'm trying to loop over and call a method on each, however, when I run this under Google Chrome, I get the following exception in the JavaScript debugger:
Uncaught TypeError: Object 0 has no method 'drawHisto'
Simplified code snippet below:
var histograms = [];
var h1 = null;
var h2 = null;
var h3 = null;
function Init() {
h1 = new Histogram(canvas1, "red");
h2 = new Histogram(canvas2, "blue");
h3 = new Histogram(canvas3, "green");
histograms = [ h1, h2, h3];
}
function Histogram(canvas, color) {
// this is my constructor
}
Histogram.prototype.drawHisto = function() {
// I will add code here to draw the histogram
}
function DrawHistograms() {
for (var h in histograms) {
h.drawHisto(); // Throws exception!
}
// h1.drawHisto() <--- this works
}
Any idea what I might be doing wrong? I've simplified the code here a bit, so if you find that the problem must be elsewhere, I can add additional context.
Thank you.
A for in loop in JavaScript does not iterate over an array's values, but rather over an object's keys. Simply use a for loop as usual:
function DrawHistograms() {
for (var i = 0; i < histograms.length; i++) {
histograms[i].drawHisto();
}
}
Or, if compatibility with Internet Explorer 8 and earlier is no issue, you may be able to use Array.forEach:
function DrawHistograms() {
histograms.forEach(function(h) {
h.drawHisto();
});
}
for (var h in histograms) {
histograms[h].drawHisto();
}
The for-in-loop in Javascript can be surprising at first: it doesn't loop over the values of the array, but rather the keys. For a straight-up array, I tend to prefer the more verbose but clearer standard for-loop:
for (var i = 0; i < histograms.length; i++) {
histograms[i].drawHisto();
}
Fun fact time! The for-in-loop can be handy for iterating over key-value mappings like {foo: 'bar', spam: 'eggs'}, but beware: it'll iterate over inherited keys, as well. For example, if some wiseguy decided to declare Object.prototype.myMethod, you'd see the keys foo, spam, and myMethod appear. The hasOwnProperty method can make the loop safe, though:
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
// proceed with confidence
}
}

Looping through Photoshop layers in Javascript

I'm trying to write a Photoshop script that will show all layers of a given name. I need to loop through all the possible nested layer sets and am using the following code:
function showBounds(layerNode)
{
for(var layer in layerNode.artLayers)
{
if (layer.name == "#bounds")
{
layer.visible = 1;
}
}
showBounds(layerNode.layerSets);
}
showBounds(app.activeDocument.doc.layerSets);
But when I run it, I get the following error:
Error 1302: No such element
Line: 5
-> for(var layer in layerNode.artLayers)
artLayers should be a property of LayerSets, so I'm confused.
This is also my first attempt at scripting PS (and using javascript), so there might be some fundamental concept I am not getting.
I think you need something more like:
function showBounds(layerNode) {
for (var i=0; i<layerNode.length; i++) {
showBounds(layerNode[i].layerSets);
for(var layerIndex=0; layerIndex < layerNode[i].artLayers.length; layerIndex++) {
var layer=layerNode[i].artLayers[layerIndex];
if (layer.name == "#bounds") {
layer.visible = 1;
}
}
}
}
showBounds(app.activeDocument.layerSets);
Also, javascripts for...in syntax doesn't work the way you think it does. It's not like a foreach loop. It loops over the property names of an object.

Categories