Undefined Array in JQuery/JavaScript - javascript

I'm having some trouble with the following piece of code:
I would like to be able to view the contents of $prisonlist in the console
I would like to be able to view the contents of $prisonlist (or $prisonlist[some value]) in the console, and to display it in the text of the div.
Essentially, whenever I do, it comes up with an error known as "undefined" - although my other functions that work with it seem to work just fine (such as the //
Code:
$counter = 0;
var $prisonlist=[];
$prisonlist[0]=1;
$('#entered').text($prisonlist[0]);
$('#s1').click(function(){
$(this).toggleClass('on off');
$counter = $counter + 1;
$('#clicks').text($counter);
$prisn = Math.ceil(Math.random()*10);
$('#prisoners').text($prisn);
$boo=$prisonlist.indexOf($prisn) //finds in array whether there is any
if ($boo==-1){
$prisonlist.push($prisn); // lists the individual inside
}
});

The declaration var $prisonlist=[];is scoped, therefore unavailable in the console where you can see only global stuff. The solutions are:
Quick yet ugly - declare $prisonlist=[]; (without the var) in the global scope.
My preferred - wherever you want to inspect the variable insert console.log($prisonlist). This will log the current value of the variable to the console.
Use a debugger

From what i can see, you are trying to use an array ($prisonlist) as an argument to the jquery text() function which only takes a string, number, boolean or function (but not an array).
You need to cast the array to a string first using JSON.stringify:
$('#element).text(JSON.stringify($prisonlist));
Ensure that #element isnt an input or textarea element since text() doesn't work on those (use val() instead).

Related

Testing innerHTML for partial string

Alright, I'm attempting to cycle through html elements within an iFrame to capture certain fields within a report. The structure of the HTML is as follows
html>frameset>frame>html>body>table>tbody>tr>td.set2>pre>(Text)
The JS I'm using to capture the .innerHTML is below
document.parentWindow.frames("Frame"B).document.all.tags("pre")[x].innerHTML
Now the above line will allow me to capture the innerHTML of the 'pre' element that contains the report name and the information I'm looking for. I'm currently working in the IE console to get my JS right before I move it to AutoHotKey but below is the function I'm attempting to use to cycle through all 'pre' elements
function preTest(){
for(x=0; x < pre.length; x++){
if(pre[x].innerHTML = "CLMPRUN"){
return pre[x].innerHTML;
} else {
return false;
}
}
};
Now, the problem is that when I run the function, it only returns "CLMPRUN". Whenever I change the test in the if statement, it returns as if I've declared pre[x].innerHTML as a variable.
Any thoughts?
Comparisons in if statements require the use of == or === operators. Using only one = means that you're assigning the value to the property.
Problem is this line: 'pre[x].innerHTML = "CLMPRUN"' You are assigning the text instead of comparing. That's why it keeps returning "CLMPRUN".
Please check here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

What is stored in variable cols in : var $cols = $('.sortdivs').on('click',function(){...});

var $cols = $('.sortdivs').on('click',function(){…});
I know that the function will run when any element with sortdivs class is clicked.
I dont know what is being stored in variable cols and how it can be used.
I tried printing variable cols and i got 'object Object' as the output.Thanks in advance.
The return value from .on is simply the collection that it was called on, for chaining purposes.
$cols, therefore, is the jQuery object containing a list of elements matched by $('.sortdivs') at the time of exection (NB: not at the time of click).
[object Object] is the string representation of any object. Try to inspect the object in another manner, for instance by using console.log($cols) to be able to get more information of just the output of a simple toString().
You can see access all the property store in variable by writing $cols[0] like ATTRIBUTE_NODE,canHaveChildren, canHaveHTML etc. You can debug and see what is inside $col[0] and based on your requirement you can manipulate them. I hope this will be helpful for you.

Why when a variable is used within another variable, its value its fixed to first declaration?

In the following code, I would expect the output to be "text something different" but instead it is "text something".
var dynamic = "something";
var thistext = "text " + dynamic;
dynamic = "something different";
console.log(thistext);
Changing the variable "dynamic" after declaring the variable "thistext", which contains it, does not change the value of "dynamic" within the "thistext".
I am sure this is something basic, but I think I do not know this rule or the best way to avoid this situation.
A Jsfiddle:
https://jsfiddle.net/k5wwpvgt/
Why when a variable is used within another variable, its value is fixed to first declaration?
You are not "using a variable within another variable". You are using a variable in an expression, the evaluated result of which happens to be being assigned to another variable. Expressions are evaluated when they are encountered, with the current values of any variables within them. There's no particular word for this behavior, since it is so fundamental to JS (and all other imperative/procedural languages).
Expressions are not dynamic definitions of calculations which are magically kept updated when their inputs change, much less magically updating variables to which the expression happened to have been assigned in the past. There is a word for such dynamic definitions of calculations: they are called functions. If you want some calculation to be dynamically redone when its inputs change, then write it as a function and call it when you need to recalculate, and if you want to (re-)assign the result of the invocation (the return value) to a variable, then do so.
Is there a way to contain a reference to a variable within another variable, and not the value of the variable when the assignment was evaluated?
Again, you're confusing variables and expressions and possibly functions. A variable is merely a box, referring to some value. It maintains no record of when or how it was assigned to, or what expression was used to calculate the value being assigned to it, nor does it have any means of automatically updating itself. Being a box, a variable cannot "contain a reference to another variable".
the best way to avoid this situation.
This is not a "situation" to be "avoided". It is the basic behavior of JavaScript.
Indeed, as others pointed out, this is expected behaviour; to do what you want, you could use a function:
var dynamic = "something";
var thistext = () => "text " + dynamic;
dynamic = "something different";
console.log(thistext());
Mind the diferences! Now thistext is a function, you must call it with (), and it gets evaluated every time.
thistext does not "contain" the variable dynamic, it contains the contents of that variable as it was at the time the expression was evaluated.
When browser will compile your javascript it will look something like
var dynamic = undefined;
var thisText = undefined;
dynamic = "something";
thistext = "text " + dynamic;
dynamic = "something different";
console.log(thistext);
when you are logging the value, you are just logging the value of thisText, which is populated when the value of dynamic is "something".
If you do the same operation after changing dynamic value you will see your desired result.
Hope this helps.

JavaScript: how to pass object value from one function to another

I am using code lines like the following in order to fetch data from an intranet website:
util.setProp(obj, "firstNameOld", $(msg).find('#fname_a').text());
Now I have another function in the same file where I want to use the above again, resp. the value of that object - currently I am hard-coding this ('Test') for test purposes:
util.setProp(obj, "firstNameNew", 'Test');
How can I pass the value from the firstNameOld object in one function to the firstNameNew object in another function ? If a solution with global variables is better here than this would work as well.
Many thanks for any help with this, Tim.
I've never used the framework that includes util But I imagine that if there is a setProp() then there has to be a getProp() or something similar.
If so, you could do something like
util.setProp(obj, "firstNameNew", util.getProp(obj, "firstNameOld"));
This also relies on the assumption that you want to copy from two properties in the same object.
If not, then pass the desired source object in the getProp() call.
My guess is that functions (or properties) are called "firstNameOld" and "firstNameNew", so the first time you get it from selector, second time you want to do the same.
Try to use the local variable like that:
var text = $(msg).find('#fname_a').text();
//
util.setProp(obj, "firstNameOld", text);
//
util.setProp(obj, "firstNameNew", text);

Programatically output variable and object names as literal text strings

I'd really like to track variables without switching between Firebug console windows or clicking around so much, so I want to draw a runtime viewer of variable names and their corresponding values that will display on the page of the app I am building.
I'd like to two functions, show(variableName) and freeze(variableName). They will output both the variable's value and the name of the variable or object as a literal string which will serve as the text label in the viewer. freeze(variableName) is the same as show(variableName) except with a setTimeOut timer for tracking loops.
I'm sure I'm missing something basic, but I haven't found out a way to get the string that comprises the name of a value programmatically so I can use it as a label. I guess I could create the table with hardcoded labels prior to runtime and just populate it with values at runtime, but I really want to generate the table dynamically so it only has those variables I specifically want to show or freeze. Simple functions:
foo1 = "Rock";
show(foo1);
foo2 = "Paper";
show(foo2);
foo3 = "Scissors";
show(foo3);
should output this via getElementById('viewer-table'):
<table>\<tr><td>foo1</td><td>Rock</td></tr><tr><td>foo2</td><td>Paper</td></tr><tr><td>foo3</td><td>Scissors</td></tr></table>
I've tried this solution:
How to convert variable name to string in JavaScript?
and eval() but it's not working for me...I dunno, shouldn't this be easy? Getting frustrated...
Thanks,
motorhobo
I am not sure you can actually get the "name" of the variable that is being passed into a function for two reasons:
1) The variable is just an identifier. In fact, you could have multiple identifiers reference the exact same object. You are (generally) passing that reference, not any actual object.
2) The show/freeze function is going to stomp on the identifier name, either through named arguments in the function declaration or by referencing them through the arguments array.
I was trying to think if there was some clever way to use the arguments.callee or the stack property on an exception in Firefox... but I can't see anything that would expose the arguments as you desire.
What I would recommend is to simply add the name of the variable and its value to a simple object, and call one of the various jsDump methods (I prefer the one in QUnit):
function show(o) {
document.getElementById("viewer-table").innerHTML = QUnit.jsDump(o);
}
// actually use the method
show({"foo1":foo1});
There's no easy way to solve this as the called function simply doesn't know the original name of the variable. You couldn't solve this with reflection even (esp. in javascript) so you'll have to pass the name of the variable to the function too. To follow the link you posted:
function show(varObject)
{
for(name in varObject)
{
alert(name + ": " + varObject[name]);
// save both name and reference to the variable to a local "to observe array"
}
}
And call it with
var test = "xxx";
show({'test' : test});
Within the for loop you could add easy variable to a monitor array and update your gui in fixed time intervalls (you can't be notifed when a signle variable changes it's value. You need some kind of global monitor/observer which exactly you're trying to create).

Categories