Array values not being changed by method - javascript

not a js expert so this might be a stupid question but...
Why does the log show that the array has changed? I was expecting the array still to be a [0,0] since the method is invoked after the console.log. Also, if I try to replace the whole array like this:
this.my_array = [1,0];
the log will still show [0,0], which is something that makes more sense to me.
What's going on?
function Y() {
this.my_array = [0,0];
this.changeIt = function() {
this.my_array[0] = 1;
};
}
var z = new Y;
console.log(z.my_array);
z.changeIt();
​

In some browsers (Chrome, for instance) console.log displays a live, interactive display of your array, not a point-in-time snapshot. So if you're looking at the console after this runs, it's been updated because of the change. Chrome also does slightly different things when you use console.log interactively in the console panel than when you use it from within a script.
You'll see what you're expecting if you display a string instead:
var z = new Y;
console.log(z.my_array.join(", "));
z.changeIt();
That shows the point-in-time snapshot you're expecting.

It works for me: http://jsfiddle.net/LyhgW/
Edit: The fact that i'm using alert makes this code work. This works around Chrome's live-feature in the console and displays a snapshot instead.

Related

Logging objects shows all properties but logging the properties individually shows 'undefined'

I'm trying to port a PHP function I built to Javascript and have been finding many differences that cause a lot of extra work. I am stuck on this one and cannot find any logic to it:
X: 95.29
Y: 27.39
testParse2.RXdec : 0.1
var curPos={};
curPos={};
console.log(curPos); //X:97.19 Y:27.39 (I expect an empty object)
console.log(curPos['X']); //undefined (seems ok but makes no sense with above)
console.log(curPos['Y']); //undefined (seems ok but makes no sense with above)
for(var Ri=0; Ri < 20; Ri++){
curPos['X'] = "";
curPos['Y'] = "";
console.log(curPos['X']); // "" (seems ok)
console.log(curPos['Y']); // "" (seems ok)
console.log(curPos); //X:97.19 Y:27.39
curPos.X = (((XY(lastPos[AV['A']], 'X')*1)+(testParse2.RXdec*1*Ri)).toFixed(10)*1);
curPos.Y = (((XY(lastPos[AV['B']], 'Y')*1)+(testParse2.RYdec*1*Ri)).toFixed(10)*1);
console.log(curPos); // X:97.19 Y:27.39 (I expect X:95.29 + 0.1 each loop Y:27.39)
console.log(curPos.X); // 95.29 (correct by why is above different?)
console.log(curPos.Y); // 27.39 (correct by why is above different?)
}
The things that confuse me the most are:
curPos gets a value before the loop even starts. The value is the
value that curPos should have after the final iteration.
during the loop the console log for curPos and curPos.X or .Y do not
contain the same values.
during the loop the console log for curPos is always the same despite changing .X and .Y each iteration
Edit: #str gave the correct explanation for the console trouble but it seems that this problem is beyond the console and actually effects the object values.
after using JSON.strigify I can see this (which is good):
console.log(JSON.stringify(testParse2));
"Xdec":97.99
"Xdec":98.09
"Xdec":98.19
but now I try to transfer the data to its final array but that final array is filled with 'lazy' values:
T['tool'][T['curTool']]['points'][lineID] = testParse2;
console.log(JSON.stringify(T));
"Xdec":98.19,"Ydec":27.39,"curX":323.19,"curY":177.39
"Xdec":98.19,"Ydec":27.39,"curX":323.19,"curY":177.39
"Xdec":98.19,"Ydec":27.39,"curX":323.19,"curY":177.39
If I stop using objects in the loop and switch to variables then build my final array like this it works:
T['tool'][T['curTool']]['points'][lineID] = {'curX' : curX,
'curY' : curY,
'TYP' : 'DR',
'lineID' : lineID,
'lineName' : lineName,};
How do you send the actual object values at a particular iteration of a loop to a different array?
Browsers evaluate objects lazily in when logging. So when you expand them after the loop, they will show the properties they have at the moment of expanding and not the ones they had when the object was logged.
You can verify that by using
console.log(JSON.stringify(curPos));
instead of
console.log(curPos);

Can't assign querySelectorAll() to a variable - weird behaviour

I was trying to crawl a very old website for a specific tag, I need to get it by it's for= attribute. So I used this piece of code.
var character = document.querySelectorAll("label[for=char_1]");
For some reason it returns an undefined, but I was using this script for a few days now and it worked like a charm. Here's the fun part. Typing that command in browsers console will result in undefined. But typing this alone:
document.querySelectorAll("label[for=char_1]");
Will return a proper NodeList. Why it won't assign to a variable...?
edit: It seems that deleting var and typing character without it will make it work. It's resolved but I would still love to get an answer to "why is this happening"?
edit2:
for (var i = 0; i < 15; i++) {
var character = document.querySelectorAll("label[for=char_" + i +"]");
console.log(character); // this will return [] from the script.
var color = character[0].children[0].style.color;
}
A simple for loop. All I get is Cannot read property 'children' of undefined. But I can type in the very same command document.querySelectorAll... and it will work in the browser and will return NodeList.
I had it working like this in a very hacky script. It worked.
var character1 = document.querySelectorAll("label[for=char_1]");
var characterColor1 = character1[0].children[0].style.color;
edit3:
var character1 = document.querySelectorAll("label[for=char_1]");
var characterColor1 = character1[0].children[0].style.color;
var character2 = document.querySelectorAll("label[for=char_2]");
var characterColor2 = character2[0].children[0].style.color;
// ...
The above code works without a single problem though. I don't think it's DOM not being ready as this code is also run from Greasemonkey script and it works. The only difference is the for loop.
var x = ""; // returns undefined, because it's a var assignment.
var elements = document.querySelectorAll('div');
That's expected behavior when pasted into the console.
edit: It seems that deleting var and typing character without it will make it work. It's resolved
I'm afraid you're creating a global scope variable now. or perhaps characters is an already defined variable in that scope.
Buhah, as I said in edit 3 "the only difference is the for loop". I was so busy trying to find an answer in the DOM-related things that I made the simplest mistake ever done in programming.
See?
char_1
With...
for(var i = 0...)
0! And I was testing char_1 in the browser instead of char_0. Which - truly - returns [] instead of something useful. Time to go on a holiday break I guess, my brain seems to be there already. :)

JavaScript DOM Dependent on Viewport Causing Strange Results

I am trying to find occurrences of a string in another string that has been pulled from the HTML document. The page is an SNMP monitor but we have been having issues in the past with CTRL + F because it only wants to find the string within the current viewport of the browser. My attempt at getting around this and not having to look through things manually was to write a script.
The issue here is that it appears the docHTML variable is only able to hold so much data and anything else is truncated. I have looked around on Stack Overflow and found that my string size is significantly less than other people have tried, so that shouldn't be the issue.
All of the IP addresses in the 'ipArray' variable do exist on the page in different locations and are in the docHTML variable when I look through it myself. When I run the doSearch function at various points in the page (viewport dependent) it gives me different results.
I really don't know what has gone wrong here as the code does work sometimes, and not other times. My goal is to have the code go through the whole page and find all missing IP's and add them to the array so that we can go ahead and add them instead of having to compare 490 IP's on a spreadsheet to up to 490 in the monitoring utility.
Thanks in advance!
var docHTML = document.documentElement.outerHTML;
var missing = [];
function doSearch(text) {
if (docHTML.search(text) == -1){
missing.push(text);
}
}
var ipArray = [
"192.168.64.236",
"192.168.64.237",
"192.168.64.238",
"192.168.64.10",
"192.168.64.11",
"192.168.64.12",
"192.168.65.40",
"192.168.65.47"
];
var Total = ipArray.length;
for(i=0;i<Total;i++){
doSearch(ipArray[i]);
}
console.log("Missing IP's: " + (Total - missing.length));
console.log(missing);
Here is the solution, not much of change, just a tweak to your logging statement. You were printing "total-missing" which is wrong. What we need is the missing count-
var docHTML = document.documentElement.outerHTML;
var missing = [];
function doSearch(text) {
if (docHTML.search(text) == -1){
missing.push(text);
}
}
var ipArray = [
"69.171.224.11",
"199.59.149.230",
"174.121.194.34",
"209.200.154.225",
"69.174.244.50",
"67.201.54.151"
];
var Total = ipArray.length;
console.log(Total);
for(i=0;i<Total;i++){
doSearch(ipArray[i]);
}
console.log("Missing IP's: " + (missing.length)); /***HERE***/
console.log(missing);
Other than this, the whole code worked for me as expected. Let me know what else/exactly is the issue. Happy to help.
The code works as intended. The issue happened to be the SNMP monitor it is running on top of. Everything on the page seems to be loaded by POST requests as you scroll. It seems to grab a few before and after which was why I was able to see it in the code and not when executing.

Javascript dropdown loop does not seem to loop

I have two dropdowns. When selecting a value from the first (bron) I want to select an entry from the second.
This is fired from the onChange of the first dropdown.
function DepId() {
var bron = document.getElementById("IDUserDepartment");
var doel = document.getElementById("IDDepartment");
var bronwaarde = bron.options[bron.selectedIndex].value;
for ( var i = 0; i < doel.options.length; i++ ) {
var doelwaarde = doel.options[i].value;
if ( doelwaarde == bronwaarde ) {
doel.options[i].selected = true;
return;
}
}
}
But this does not work.
EDIT: for whatever reason, I never get a match. When I hardcode any of the values, and then do: doel.options[hardcodedvalue].selected=true, the option is selected. When I test for window.alert(doelwaarde) inside the loop, this always returns zero.
Any suggestions?
Your code should work, I see nothing wrong with it. If I may make three suggestions:
You might want to use jQuery: simpler code, better multi-browser support.
Use console.log instead of a window alert for debugging purposes: less intrusive, won't interrupt your testing (have a look at the developer console of your browser).
You might want to use English names for your variables, controls, etc. More developers will be able to read it, besides English is often shorter than Dutch ;)

jQuery object never changing except for first time

I ran into a problem with an object which I'm trying to modify. The object has a certain amount of keys in the format key_yyyy-mm-dd. When certain inputfields lose focus, I trigger a function to modify the object. This function is as follows:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
});
}
.no_hotel are the textboxes that trigger the function, and they also provide a value which I want to put in my object.
Now, say I put 3 in my first text box, a console.log will return the following object:
Object
key_2011-08-21: 3
key_2011-08-22: 0
key_2011-08-23: 0
key_2011-08-24: 0
key_2011-08-25: 0
However, the next time I put something in the textbox (or another textbox that should trigger the function), it DOES trigger, however the object returned remains the same. So instead of changing the first number to, say, 5, it will just return 3 again.
I have no idea why. My code seems pretty straightforward, and a console.log of day and $(this).val() returns the right values. It's just my object that doesnt get updated.
Does anyone have any idea? Thanks a lot!
EDIT:
hotelBooking is initialized right after $(document).ready():
var hotelBooking = {};
The method that calls updateHotelBooking is the following:
$(".roomrequest").blur(function()
{
updateHotelBooking();
});
EDIT2: JSFiddle: http://jsfiddle.net/pBYeD/2/
it has to do with something with the console rather than your code, if you change the logging code to this, you will see that you have the correct values:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
**logObject(hotelBooking);**
});
}
function logObject(hotelBooking){
for(var i in hotelBooking){
console.log(i+": "+hotelBooking[i]);
}
console.log("------");
}
Are you sure the problem does not come from the debugger output?
As far as i can see in my chrome output, if i let the fiddle as is, the object doesn't appear to change in the console (just the number on the left takes a +3). However if I add something like console.log(hotelBooking["key_" + day]); just before or after, it's shown as changing.

Categories