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);
Related
This question already has answers here:
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 4 years ago.
I'm currently in the process practicing using electron, but I'm quite new with javascript and I've come across a problem which has me completely baffled. I have the following code:
function getPaths() {
var dirPath = document.getElementById("mdir").innerHTML;
var filePaths = [];
fs.readdir(dirPath, function(err, dir) {
for(var i = 0, l = dir.length; i < l; i++) {
var filePath = dir[i];
filePaths.push(dirPath + "/" + filePath);
}
});
console.log(filePaths);
console.log(filePaths.length);
}
Which is supposed to look into a directory defined by dirPath, then it loops through and obtains the full path of all files in that directory. It appends them to an array, and then at the bottom, it logs the array to the console, followed by the length of the array.
What is baffling me is that given that code, the array logs to the console like expected, but then the console logs zero as the length. My current thinking is that it's got something to do with scope, but that doesn't make sense because I'm declaring the array, filePaths in the function above the one that's running. Unless I've missed something. Could anyone point out what I'm doing wrong?
readdir is asynchronous. It won't get the results right away. You should use the filePaths inside the callback. The only reason why the console shows the value is because the console evaluates the array when you unfold it.
When you press the little arrow on the left, put the mouse on the i box on the right. What happens is that the console keeps a reference to the array, so when the user unfolds the array it then shows the current value of the array. But when you log filePaths.length the array is empty because readdir didn't finish reading yet, that's why you get 0. But by the time you open the console and press that arrow, readdir will have already done reading and the console will print the current value of the array (after it's been filled).
Example to demonstrate the problem: (not a solution, it's just to understand what is really happening)
Open the browser console and try this code and see what happens:
var arr = [];
setTimeout(function() {
arr.push(1, 2, 3);
}, 5000);
console.log(arr.length);
console.log(arr);
Here the array and it's length are both logged before the array is filled. The array will be filled after 5 seconds. So the output will be 0 and a string representation of the array array[]. Now because arrays could have tons of data, the console won't show that data until the user unfolds the array. So what the console does is keep a reference to the array until the user press the unfold arrow. If you unfold the array before 5 seconds you'll see that the array is empty (not filled yet). If you wait until the 5 seconds pass then unfold it, then you'll see that it's filled, even though it was logged as an empty array.
Note: Also, the line that get logged to the console (something like > Array(0)) is just a string representation of the object/array at the moment the log happens. It won't get updated if the object/array changes. So that also may seem confusing sometimes.
I hope it's clear now.
Just to expand on #ibrahim-mahrir 's answer, they means like this
function getPaths() {
var dirPath = document.getElementById("mdir").innerHTML;
var filePaths = [];
fs.readdir(dirPath, function(err, dir) {
for (var i = 0, l = dir.length; i < l; i++) {
var filePath = dir[i];
filePaths.push(dirPath + "/" + filePath);
}
console.log(filePaths);
console.log(filePaths.length);
});
}
I have an array with 4 elements and in one scenario I want to pop one element from the array. But after pop array gives the same result as before.
I have checked in the console window and there I have find a different behavior like array length is 4 and it shows like it has 5 elements.
I have tried to remove the empty elements also but still the same issue is coming .
var brudcrumbDataArray=JSON.parse(brudcrumbDataString);
brudcrumbDataArray = brudcrumbDataArray.filter(function(n){ return n != undefined });
console.log(brudcrumbDataArray)
brudcrumbDataArray.pop();
console.log(brudcrumbDataArray)
Her is the array :
[{"name":"Dashboard","url":"","path":"","class":"icon-home2 position-left","type":"MainMenu","queryParams":""},{"name":"Main","url":"#/dashboard","path":"/dashboard","class":"","type":"SubMenu","queryParams":""},{"name":"Sub Accounts","url":"#/account/customers","path":"/account/customers","class":"","type":"SubMenu","queryParams":""},{"name":"End Users","url":"#/account/endusers","path":"/account/endusers","class":"","type":"SubMenu","queryParams":""},{"name":"Profile","url":"#/user-dashboard","path":"/user-dashboard","class":"","type":"SubMenu","queryParams":""}]
After pop also array gives the same data and same length. Can someone help me to solve this issue ?
Snippet, check your console to see the problem:
var brudcrumbDataString =`[{"name":"Dashboard","url":"","path":"","class":"icon-home2 position-left","type":"MainMenu","queryParams":""},{"name":"Main","url":"#/dashboard","path":"/dashboard","class":"","type":"SubMenu","queryParams":""},{"name":"Sub Accounts","url":"#/account/customers","path":"/account/customers","class":"","type":"SubMenu","queryParams":""},{"name":"End Users","url":"#/account/endusers","path":"/account/endusers","class":"","type":"SubMenu","queryParams":""},{"name":"Profile","url":"#/user-dashboard","path":"/user-dashboard","class":"","type":"SubMenu","queryParams":""}]`;
var brudcrumbDataArray=JSON.parse(brudcrumbDataString);
brudcrumbDataArray = brudcrumbDataArray.filter(function(n){ return n != undefined });
console.log(brudcrumbDataArray)
brudcrumbDataArray.pop();
console.log(brudcrumbDataArray)
A result on the console seems to be correct. Both the logs on the console window are showing the result after the operation. Why is the first log showing a result in it? because, in javascript, complex objects get stored by reference, that's why your first log does show a result in it too.
Store by reference? what does it mean? : https://docstore.mik.ua/orelly/webprog/jscript/ch04_04.htm
Try below one,
var brudcrumbDataString =`[{"name":"Dashboard","url":"","path":"","class":"icon-home2 position-left","type":"MainMenu","queryParams":""},{"name":"Main","url":"#/dashboard","path":"/dashboard","class":"","type":"SubMenu","queryParams":""},{"name":"Sub Accounts","url":"#/account/customers","path":"/account/customers","class":"","type":"SubMenu","queryParams":""},{"name":"End Users","url":"#/account/endusers","path":"/account/endusers","class":"","type":"SubMenu","queryParams":""},{"name":"Profile","url":"#/user-dashboard","path":"/user-dashboard","class":"","type":"SubMenu","queryParams":""}]`;
var brudcrumbDataArray=JSON.parse(brudcrumbDataString);
brudcrumbDataArray = brudcrumbDataArray.filter(function(n){ return n != undefined });
console.log(JSON.parse(JSON.stringify(brudcrumbDataArray)))
brudcrumbDataArray.pop();
console.log(JSON.parse(JSON.stringify(brudcrumbDataArray)))
Look closely here, we are doing deep data copy with using JSON operations, by surrounding object in JSON.parse(JSON.stringify( )) and it won't point to reference anymore now.
And log will be more clear as below,
it showing because the reference to the same object so when you pop last element the object get modified and shows the length as 4 so the first consoled object also get updated.
var brudcrumbDataArray = [{"name":"Dashboard","url":"","path":"","class":"icon-home2 position-left","type":"MainMenu","queryParams":""},{"name":"Main","url":"#/dashboard","path":"/dashboard","class":"","type":"SubMenu","queryParams":""},{"name":"Sub Accounts","url":"#/account/customers","path":"/account/customers","class":"","type":"SubMenu","queryParams":""},{"name":"End Users","url":"#/account/endusers","path":"/account/endusers","class":"","type":"SubMenu","queryParams":""},{"name":"Profile","url":"#/user-dashboard","path":"/user-dashboard","class":"","type":"SubMenu","queryParams":""}]
//var brudcrumbDataArray=JSON.parse(brudcrumbDataString);
var newBrudcrumbDataArray = brudcrumbDataArray.filter(function(n){ return n != undefined });
console.log(brudcrumbDataArray)
newBrudcrumbDataArray.pop();
console.log(newBrudcrumbDataArray)
I know there are several issues with JavaScript Array.push() method posted here, but I can't get the following example to work:
First of all, i got a global Array:
var results = new Array();
for (var i = 0; i < X.length; i++) {
results[i] = new Array();
}
Now this array should be filled on a button-event. All I want is to fill the Array with new Arrays and push some data to them. The following code should check if results[x][y] already is an Array (and create one if it's not) and push data to it.
So, in the end, there should be an Array (result) that contains X.length Arrays filled with an unknown number of new Arrays, each of them containing an unknown number of data:
function pushResult(result) {
if (typeof results[currentStim][currentDist] == 'undefined') {
results[currentStim][currentDist] = new Array();
}
results[currentStim][currentDist].push(result);
}
Problem is: It just doesn't work. I made sure that currentStim is never out of bounds, I made sure that the "if"-Statement is only accessed when needed (so the Array isn't overwritten with a new one) and I watched the return-value of push(), always throwring back a number representing the new array length. As expected, this number increases evertime a value is pushed to an Array.
However, when I finally call:
document.getElementById('results').value = JSON.stringify(results);
to pass results to my PHP-script, something like this will be passed:
[[],[[1]],[],[]]
push()was called MUCH more often than once (at least "1" is one of the results I wanted to be stored) and, as described, always returned an increasing arrayLength. How does that work? What happened to my data?
I testet this on Chrome as well as on Firefox, same result. It might be interesting that a seperate loop draws to a Canvas the same time, but that shouldn't interupt Array-Handling and onKey-Events, right?
Hope u can help me,
MA3o
EDIT:
pushResult is called like this:
// Handles Space-Events
function pushed(event) {
if (event.which == 32 && stimAlive) {
pushResult(1);
hitCurrent = true;
}
Where hitCurrent and stimAlive are just flags set somewhere else. Some code further the function pushedis registered as an event listener:
document.onkeydown = function(event) { pushed(event)}
All the functions are called correctly. Adding console.log(results) to every loop just shows the right Array, as far as I can see.
According to the comments, the problem might be that "currentDist" can be a float value.
Ladies and gentlemen,
I'm stuck. I've been pondering this (and obviously have failed since I'm asking for your valuable assistance) in trying to get my code to work.
I need to come up with a simple (...I'm sorry, i'm new to this) code that prompt users to keep entering names using a loop. If the user does not enter 'q'(without quotes) and if the value entered is NOT null, then the value entered should be added to the array (in my case, names).
If the user enters 'q', the loop should stop, 'q' will not be entered in the array and the list of names should be printed (through the second function in my code).
Here's what I have so far... I can make the code work if I tell the loop to run i<5... it runs 5 times and then it stops. But it fails if i do i < names.length..it causes it say that length is null or not an object (on line 10). That's problem one. And for the life of me, I can't figure out how to add the logic that will run the loop until user enters q.
Please help!
Thank you.
function getNames(){
var names = new Array();
for(i=0;i<names.length;i++){ /*if i do i=0;i<5;i++, the code works; it doesn't with this*/
names[i] = prompt("Enter an item to add to the Name list (enter \'q\' to quit","");
}
printNames(names);
}
function printNames(names) {
for(x=0; x < names.length;x++){
document.write(names[x] + '<br />');
}
}
getNames();
printNames();
I am sure somewhere in your class/book it talks about while loops. So you want to use a while loop if you want them to keep entering without a limit.
while (myCondition===true) {
//do something
}
Now look at your for loop and figure out why it is failing.
for(i=0;i<names.length;i++)
Look at what it is doing:
i = 0
names.length = 0
Is 0 < 0?
Well to start with Problem 1:
Your names array begins with a length property of 0 and so your first for loop doesn't run because 0 is not less than 0.
Which leads to Problem 2:
Again since nothing was entered into your names array your second for loop again does nothing and doesn't execute document.write because the length property of your array is still 0.
I'm trying to create my own JS Password Strength Meter.
It was working before but i didn't like how it worked so I tried using
{score +=10;}
Instead of just:
score++
This is my code:
http://jsfiddle.net/RSq4L/
Best Regards,
Shawn,
Hope someone can help
Multiple issues:
Your passwordStrength() function was not defined in the global scope in the jsFiddle so it wasn't getting called. This is probably an artifact of how you set up the jsFiddle, perhaps not an issue in your real code.
The method of getting the appropriate ratingMsg will not work because you don't have array values for every possible score so many scores will generate an "undefined" ratingMsg.
Your CSS classes are also sparse so there are many score values that they will not match for either and no appropriate CSS class/style will be in effect. If you want a specific class for each rating value, then perhaps you should put the classname in the ratings array so it can be fetched from there along with the ratingsMsg.
For the first issue, in your jsFiddle, you also have to make sure the password processing function is defined in the global scope. The way your jsFiddle is set up, it is not (it's in the onload handler). You can fix this in the jsFiddle by just setting the first drop-down in the upper left to "no wrap (head)".
For the second issue, you are using:
ratingMsg[score]
but, your array is a sparse array not guaranteed to have an entry for most possible scores. You simply can't do it that way because many elements you access will have undefined values which won't give you a meaningful message. For example, if score was 15, you would be accessing ratingMsg[15], but there is no value in that space in the array so you won't get a meaningful rating message.
The solution is to find a different way to select the right message. The simplest way would just be an if/else if/else if statement that would check which range the score is in and set the appropriate msg. There are more elegant table driven ways, but all will involve searching through a data structure to find which two values the current score is between and using that msg.
If you look at this jsFiddle http://jsfiddle.net/jfriend00/dA7XC/, you'll see that your code is getting called, but it only hits values in the array sometimes.
And, here's a rewritten algorithm that finds the appropriate msg no matter what the score show in this fiddle: http://jsfiddle.net/jfriend00/jYcBT/.
It uses a data structure like this:
var ratingMsg = [
0, "Unclassified",
10, "Weak",
20, "Fair",
50, "Better",
60, "Medium",
70, "Good",
90, "Strong"
];
and a for loop like this to get the appropraite ratingMsg:
for (var i = ratingMsg.length - 2 ; i >= 0; i-=2) {
if (score >= ratingMsg[i]) {
msg = ratingMsg[i+1];
break;
}
}
Here you go: http://jsfiddle.net/RSq4L/11/
The first problem is that in your fiddle you have the onLoad option set, so your passwordStrength function is not actually being declared in the global scope. It is being declared inside of the onLoad block that jsFiddle wraps your code with. This causes the page to error out when the keypress handler tries to invoke the function.
You can fix this problem in several different ways:
By explicitly declaring the function as global as per my example above.
By choosing one of jsFiddle's "no wrap" options instead of onLoad.
By dynamically binding your event-handler instead of setting it through the element's onkeydown attribute in the markup.
The second problem is how you are keying your score messages. You have:
var ratingMsg = new Array(0);
ratingMsg[0] = "Unclassified";
ratingMsg[10] = "Weak";
ratingMsg[30] = "Fair";
ratingMsg[50] = "Better";
ratingMsg[60] = "Medium";
ratingMsg[70] = "Good";
ratingMsg[90] = "Strong";
...and you lookup the message by doing ratingMsg[score]. This will only work if the score exactly matches one of your indices. And based upon your math this will not always be the case.
I would suggest doing something like:
ratingMsg = {};
ratingMsg[0] = "Unclassified";
ratingMsg[10] = "Weak";
ratingMsg[30] = "Fair";
ratingMsg[50] = "Better";
ratingMsg[60] = "Medium";
ratingMsg[70] = "Good";
ratingMsg[90] = "Strong";
function closestRating(score) {
var bestKey = 0;
var bestMatch = 100;
for (var key in ratingMsg) {
if (key <= score && score - key < bestMatch) {
bestMatch = score - key;
bestKey = key;
}
}
return ratingMsg[bestKey];
}
On an unrelated note, are you sure you want to be using onkeydown? I think onkeyup would work better.
Your fiddler script had several errors. Here's the corrected one: new script.
You were missing a semicolon here: document.getElementById("passwordDescription").innerHTML = "" + ratingMsg[score] + ""
You forgot to escape '^' on your regular expression
I just wrote this for it:
Jquery Plugin for password strength forcing