JavaScript iterating through all variables in Page - javascript

I wanted to get all JavaScript Variables. So I followed instructions in this topic and it worked smoothly.
Get all Javascript Variables?
Now I also want to get all strings, that are not declared as variable. For example in below code when I iterate through this I get the value of variable hello in output. However, since "Passing My Message" string is not declared as variable, I don't get this string in output.
<script>
function MyFunction(msg){
alert('Message Passed : '+msg)
}
var hello = "AAA";
MyFunction("Passing My Message");
for (i in this){
console.log(i + " : " + eval(i));
}
</script>
Now my question is, is there any way I can get the Passing My Message string in output.

You won't. When you call the function MyFunction it creates the variable msg. When the function finishes the variable msg is removed.
If you checked inside the MyFunction function then you would see the msg variable but you won't see it at any other time.

Related

How forEach works if we pass more than one argument?

I saw a javascript code where we have to print an array in the console.
I want to know how the value of i is initialised to 0 and how it is incremented.
Here is the code:
var tos = ["Hello","Hi"];//To print this arraytos.forEach(fuction(toso,i){console.log(i + " " + toso);});
I think youre messing up forEach and a regular for loop. The forEach function is a regular (built in) function, that behaves quite similar as this:
function forEach(func){ // here you pass a function as parameter
for(var i=0;i<this.length;i++){
func(this[i],i);//now it is called
}
}
So in your case, the built in function will do:
func("Hello",0);
func("Hi",1);
And thats what your parameters toso and i catch...
In your case you could also do:
tos.forEach(console.log);

creating variable names from parameters in javascript

I was wondering if it is possible to create variable names from parameters passed to a function in javascript. Something like this:
function createVar(number) {
var "number" + number;
}
createVar(1)
I'm new to Stack Overflow and programming, so any help would be appreciated.
You could attach this to the window object, but note it will be global. For example:
function createVar(varName, value) {
window[varName] = value;
}
createVar("test", "Hello World");
alert(test); // Outputs "Hello World".
It is possible to interpret Object as associative array where you specify index and get value by name of index ( hash ):
var x = Array();
x[number] = value;
Single variable name is for programmer, and the code would be hard to maintain and understand when you set variable dynamically in code.
Honestly, I don't see why this would ever be useful, because every time you want to use the variable you'd have to search for it with your number argument.
However, you can do it, albeit not the exact way you had described:
function createVar(number){
eval("var number" + number.toString() + ";");
}
however, this variable will only be accessible within the function, to make it global assign to the window object:
function createVar(number){
window["number" + number] = 15; // creates "global" variable
}
As I've stated before, however, I don't see this being useful, [i]ever[/i], if you want to stratify values by numbers you'd be much better off with an array.

Name undefined error

I am making a div and in its onclick function I am calling function Remove() to which I am passing its id and name. But when I use name in my remove function, an undefined error is thrown. For example, I call Remove(1,xyz) and then in the Remove function I am unable to access xyz; it's showing me xyz is not defined.
Here is my jQuery code which calls the Remove function:
$("#h2-"+id).append("<div id = 'c2-"+id+"' onclick = 'Remove("+id+","+name+")' class='clear_btn1'> </div>");
and here is my Remove function:
function Remove(i, name){
alert("I am deleting " +name);
var sender = "<?php echo $user_check?>";
var receiver = name;
console.log("Name is " +sender);
console.log("receiver is " +receiver);
}
The value of i is coming perfectly fine but I cannot access name in my function.
Change your code as below
$("#h2-"+id).append("<div id = 'c2-"+id+"' onclick = \"Remove("+id+",'"+name+"')\" class='clear_btn1'>sdfsdf sdfsdf</div>");
What is saved in onclick is actually Remove(id,name). This looks okay at first look, but...
Say id=10 and name="Mark".
You would be calling Remove(10,Mark), which is not what you want. Mark would be treated as a variable. You therefore need to put additional quotes enclosing name to treat it as a string.
You should, of course, escape the additional quotes you would add.
You need to call Remove(10,"Mark"). Notice the quotes.

Put a variable between double quotes

I have a small question:
I have a function in javascript.
var func = function(variable)
{
result = variable;
}
If I call
func(rabbit);
I need the result to be "rabbit".
I cannot figure out how to put the variable between the two quotes.
Assuming rabbit is supposed to be a string:
func("rabbit");
If rabbit is actually a variable, then there's no way to do this because the variable (meaning the implementation's representation of a variable) isn't actually passed to the function, but rather its value is.
Actually there's an ancient way to retrieve the variable name.
var func = function(variable)
{
console.log(variable); // outputs "white"
console.log(arguments.callee.caller.toString().match(/func\((.*?)\)/)[1]); // outputs "rabbit"
}
rabbit = 'white';
func(rabbit);
See it running http://jsfiddle.net/Q55Rb/
You could do this
function whatever(input) {
return '\"' + input + '\"';
}
result should be in quotes
I could not tell from your question whether you wanted "rabbit" to be the property name, or the value. So here is both:
var func = function(variable) {
window[variable] = 'abc'; // Setting the variable as what is passed in
window.result = variable; // Normal
}
func('rabbit'); // Will set both window.rabbit to 'abc', and window.result to 'rabbit'
I wouldn't advise setting global variables, though. More info
Ok I thought that was my problem. Now I'm pretty sure that's not it but I have no clue what it is then.
I have this in my function:
defaults = {title :{'pan':-1,'left':0,'volume':0.30,'top':111}};
Where title is a variable from the function. But as a result I get title in defaults instead of the actual title stored in the variable named title. Do you understand me?

Remembering the last value passed to a JavaScript function called on click

Below is my code fragment:
<div onclick = "myClick('value 1')">
button 1
</div>
<div onclick = "myClick('value 2')">
button 2
</div>
Basically when I for each click on a different div, a different value will be passed to the JavaScript function.
My Question is how can I keep track of the value passed in the previous click?
For example, I click "button 1", and "value 1" will be passed to the function. Later, I click on "button 2", I want to be able to know whether I have clicked "button 1" before and get "value 1".
Just add it to a variable in your script:
var lastClicked;
var myClick = function(value) {
lastClicked = value;
};
You can define somekind of variable, like var lastUsed;
add additional line to your function:
var lastUsed = null;
function myClick(value){
prevClicked = lastUsed; //get the last saved value
...
lastUsed = value; //update the saved value to the new value
...
}
And here you go
You need a variable. Variables are like little boxes in which you can store values. In this case, we can store the value that was last passed to the function myClick.
In Javascript, you can define a variable like this:
var lastClickedValue;
You can "put" a value into that variable. Let's say you want to put your name in there. You would do this:
lastClickedValue = 'sams5817';
Now here's the tricky bit. Variables have "scope". You might want to think about it as their "life-time". When a variable reaches the end of its scope, you cannot read or write to it anymore. It's as if it's never been. Functions define a scope. So any variable you define in a function will disappear at the end of the function. For example:
function myClick(value)
{
var lastClickedValue;
alert('lastClickedValue is = ' + value);
lastClickedValue = value;
}
That looks almost right, doesn't it? We declared a variable, display its last value, and update it with the new value.
However, since the lastClickedValue was declared in the function myClick, once we've reached the end of that function, it's gone. So the next time we call myClick, lastClickedValue will be create all over again. It will be empty. We call that an "uninitialized" variable.
So what's the problem? We're trying to remember a value even after the end of myClick. But we declared lastClickedValue inside myClick, so it stops existing at the end of myClick.
The solution is to make sure that lastClickedValue continues to exist after myClick is done.
So we must delcare lastClickedValue in a different scope. Luckily, there's a larger scope called the "global scope". It exists from the moment your page loads, and until the user moves on to another webpage. So let's do it this way:
var lastClickedValue;
function myClick(value)
{
alert('lastClickedValue is = ' + value);
lastClickedValue = value;
}
It's a very small difference. We moved the declaration of the variable lastClickedValue to be outside the function myClick. Since it's outside, it will keep existing after myClick is done. Which means that each time we call myClick, then lastClickedValue will still be there.
This will let you know what the last value passed to myClick was.
Finally, I'd like to advise you to look for some kind of Javascript tutorials. I wish I knew of some good ones to recommend, but I'm certain you can find a few on the Internet. If you try to write programs before understanding what you're doing, you'll find yourself producing work that is less than what you're capable of. Good luck!
I suppose you need something like this
var clickedButtons = [];
function myClick(value){
...
clickedButtons.push(value);
...
}
I am surprised that no one else mentioned this, but since functions are first class objects in JavaScript, you can also assign attributes and methods to functions. So in order to remember a value between function calls you can do something like I have with this function here:
function toggleHelpDialog() {
if (typeof toggleHelpDialog.status === 'undefined')
toggleHelpDialog.status = true;
else
toggleHelpDialog.status = !toggleHelpDialog.status;
var layer = this.getLayer();
if (toggleHelpDialog.status) layer.add(helpDialog);
else helpDialog.remove();
layer.draw();
}
Here I have added an attribute named 'status' to the toggleHelpDialog function. This value is associated with the function itself and has the same scope as the toggleHelpDialog function. Values stored in the status attribute will persist over multiple calls to the function. Careful though, as it can be accessed by other code and inadvertently changed.
we can leverage javascript static variables
One interesting aspect of the nature of functions as objects is that you can create static
variables. A static variable is a variable in a function‘s local scope whose value persists across
function invocations. Creating a static variable in JavaScript is achieved by adding an instance
property to the function in question. For example, consider the code here that defines a function
doSum that adds two numbers and keeps a running sum:
function doSum(x,y){
if (typeof doSum.static==='undefined'){
doSum.static = x+y;
}else{
doSum.static += x+y;
}
if (doSum.static >= 100){doSum.static = 0;doSum.static += x+y;}
return doSum.static;
}
alert(doSum(5,15))
alert(doSum(10,10))
alert(doSum(10,30))
alert(doSum(20,30))

Categories