473,403 Members | 2,222 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

alert('x='+x)

How to write a function f(x) or f('x') so that it produces the same output
as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the variable
value one would save a lot of typing during one's lifetime.

I think there is so simple solution for this that I probable will feel very
embarrassed after getting the answer. So I blush in advance :).
Jul 23 '05 #1
15 3188
optimistx wrote on 05 apr 2004 in comp.lang.javascript:
How to write a function f(x) or f('x') so that it produces the same
output as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the
variable value one would save a lot of typing during one's lifetime.


function toAlert(x){
alert('toAlertParameter = "'+x+'"');
}

toAlert('Try me out')
toAlert( 355/113)

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 23 '05 #2

"Evertjan." <ex**************@interxnl.net> kirjoitti viestissä
news:Xn********************@194.109.133.29...
optimistx wrote on 05 apr 2004 in comp.lang.javascript:
How to write a function f(x) or f('x') so that it produces the same
output as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the
variable value one would save a lot of typing during one's lifetime.


function toAlert(x){
alert('toAlertParameter = "'+x+'"');
}

toAlert('Try me out')
toAlert( 355/113)

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)


Thanks Evertjan for trying. I was probably a bit unclear when asking. After
posting I could not resist trying to find a solution anyhow. One way was to
use the 'evil' eval function like this:

alertt=function(){
var s='';
for (var i=0;i<arguments.length;i=i+1){
s+=arguments[i]+'='+eval(arguments[i])+'\n';
}
alert(s);
}
// example usage:
var x=3;
var y='abc';

alertt('x','y','document.title');
// the output is an alert box with e.g.
x=3
y=abc
document.title=example document title

and
alertt('x') gives an alert box with text
x=3

Sorry to bother readers perhaps in vain. Hopefully the code is useful for
someone else except me :).

By the way, is there a way to avoid eval() above?


Jul 23 '05 #3
optimistx wrote on 05 apr 2004 in comp.lang.javascript:
By the way, is there a way to avoid eval() above?


There is always a way to avoid evil [remember sunday school]:

toAlert=function(){
var s='';
for (var i=0;i<arguments.length;i++)
s+=arguments[i]+' = '+window[arguments[i]]+'\n';
alert(s);
}
var x=5
var y=x*x
toAlert('x','y')
this does only work for global variables,
not for 'document.title',
nor for '2*3*4'.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 23 '05 #4
optimistx wrote:
<snip>
alertt=function(){
var s='';
for (var i=0;i<arguments.length;i=i+1){
s+=arguments[i]+'='+eval(arguments[i])+'\n';
}
alert(s);
} <snip> Sorry to bother readers perhaps in vain. Hopefully the code is useful
for someone else except me :).


The code is unlikely to be of that much use to you either. You will be
able to display a number of global variable names and values along with
the property accessors and values of property accessors that use
absolute references. But you won't have much joy with local variables,
property accessors relative to the - this - keyword and many similar
conditions. Consider:-

function demonstration(s, p){
var d = document;
for(var c = 0;c < 2;c++){
alertt('c','s','p','d.title','arguments[2]');
}
}

The result would be; 'c' is probably undefined, unless there is also a
global variable called 'c' and that would not be the 'c' that was
interesting in the context of the call, 's' refers to the string that is
being built inside the - alertt - function, 'p' is like 'c' as it is a
parameter to the outer function, 'd.title' will produce an error, unless
there is a global variable 'd' that refers to an object, and
'arguments[2]' will refer to the string 'p' (the third argument to -
alertt). Nothing that might be interesting in the context of the call
to - alertt - is reported.

As an aid to development it would only really be useful in referring to
global variables and, as general programming advice is to create as few
global variables as possible, it will have limited practical
applications. It may even encourage you to adopt an inappropriate
programming style in order to make use of this tool.

Richard.
Jul 23 '05 #5
Evertjan. wrote:
Richard Cornford wrote on 05 apr 2004 in comp.lang.javascript:
The code is unlikely to be of that much use to you either.
You are making a mistake here Richard.

Code in this NG is not only useful for execution but also,
and perhaps even more so for discussion and learning.


Fair enough. I was thinking of the - alertt - function in terms of how
useful it would be for the purpose for which it was designed (alerting
name value pairs of variables, etc). Its limitations may well prove
educational.
This code as such is perhaps totally unuseful in use, but I at least
learned that the window[x] form of global variables doesn't work if x
is a formula.

That is I did know it, otherwise it would be equally evil as eval(),
but now I is in my active memory for a while.

To construct a global variable name dynamicly it is very usefull:

var window["varNr"+n*2] = 7*n;


I would suggest that the global object is not the best repository for
dynamically created properties and their corresponding values.

Richard.
Jul 23 '05 #6
Thanks to Richard Cornford for revealing the limitations of the proposed
code. It saved me a lot of testing time and possible frustration, and the
remarks about good coding style are necessary for me to remember. Evertjan's
attitude makes me feel happy, thanks :).

When talking about inner functions there was an encouraging note from an
expert (was it Crockford? His home pages are a wonderful source of ideas)
that 'almost anything can be done with those'. It were a bit strange that
one could calculate the global variable value when knowing is name (as a
string), but not local. The flexibility of the Javascript language has
surprised me, but are the limits here now?
Jul 23 '05 #7
JRS: In article <tR****************@reader1.news.jippii.net>, seen in
news:comp.lang.javascript, optimistx <op*************@hotmail.com>
posted at Mon, 5 Apr 2004 09:17:18 :
How to write a function f(x) or f('x') so that it produces the same output
as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the variable
value one would save a lot of typing during one's lifetime.


It cannot be done with f(x), as the name is not then passed. But

function f(x) { alert(x+'='+eval(x)) }

will do it.

A general expression can be passed; f("3+5"), f("Math.sqrt(+X)").

Since that will not show the difference between x="" & x=" ", you may
want a different version for strings,

function s(x) { alert(x+'="'+eval(x)+'"') }

There is a way, I suspect, of doing it without eval.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #8
In article <tR****************@reader1.news.jippii.net>,
"optimistx" <op*************@hotmail.com> wrote:

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the variable
value one would save a lot of typing during one's lifetime.


Instead of using an alert, I write all of my debug information to a
popup window. This saves me from having to press enter for every alert.

See "Re: Debug - Your own console":
http://groups.google.com/groups?hl=e...charles-FF349F.
22451509022004%40news02.west.earthlink.net

Robert
Jul 23 '05 #9
rh
Dr John Stockton wrote:
optimistx <op*************@hotmail.com>
posted at Mon, 5 Apr 2004 09:17:18 :
How to write a function f(x) or f('x') so that it produces the same output
as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the variable
value one would save a lot of typing during one's lifetime.
It cannot be done with f(x), as the name is not then passed. But

function f(x) { alert(x+'='+eval(x)) }

will do it.

A general expression can be passed; f("3+5"), f("Math.sqrt(+X)").

Since that will not show the difference between x="" & x=" ", you may
want a different version for strings,

function s(x) { alert(x+'="'+eval(x)+'"') }


Or, something in the nature of the following framework:

ALERT = eval; // Slip sheep's clothing on nasty wolf!

function fmt(arg) { // Create eval-ready alert string
var varList = arg.split(",");
for (var k= 0, str = ""; k < varList.length; k++) {
str += "+'\\n"+varList[k]+ ": '"
+"+ (( typeof "+varList[k]+" == 'object') ? Dumper("+varList[k]
+") : "+varList[k]+"+ ' type: '+ typeof "+varList[k]+" )";
}
return "alert(" +str.substr(1)+")";
}

function test(a,b) {
var c = "local variable";
var d= document.title;
var e = { propName : "property value" };
ALERT(fmt("a,b,c,d,e"));
}

test("arg1",2);

which extends the display to include objects.
___________
Notes:

- Creating the ALERT reference to the built-in "eval" function
appears to work in IE 6 and Opera 7.11. It fails in Netscape/Mozilla
in that local execution context is not maintained (however, the above
works if eval is used without substitution).

- Dumper is an object formatting function from the following
reference:

<url:http://groups.google.ca/groups?q=%22matt+kruse%22++group:comp.lang.javascr ipt&hl=en&lr=&ie=UTF-8&group=comp.lang.javascript&scoring=d&selm=c4ehko 01c6%40enews2.newsguy.com&rnum=7>

- It appears that the line

DumperTagProperties["OPTION"] = ['text','value','defaultSelected'];

needs to be included (at least currently) if the object to be
formatted references an element from the DOM (as per the last line of
the example given in the reference). Without it, the library code
loops when executing Dumper(x);.
___________
There is a way, I suspect, of doing it without eval.


I confess to being doubtful. It would seem to me that eval is the only
mechanism available that is going to allow insertion/execution of code
that takes on the required context.

../rh
Jul 23 '05 #10
rh wrote:
<snip>
ALERT = eval; // Slip sheep's clothing on nasty wolf! <snip> Notes:

- Creating the ALERT reference to the built-in "eval" function
appears to work in IE 6 and Opera 7.11. It fails in Netscape/Mozilla
in that local execution context is not maintained (however, the above
works if eval is used without substitution).

<snip>

Failure should be expected in that context as ECMA 262 3rd ed. Section
15.1.2.1 ends:-

| If value of the eval property is used in any way other than
| a direct call (that is, other than by the explicit use of
| its name as an Identifier which is the MemberExpression in
| a CallExpression), or if the eval property is assigned to,
| an EvalError exception may be thrown.

Richard.
Jul 23 '05 #11
Fox
sorry for the top post... but the subject has been made thoroughly familiar.

No need for eval...
and, if I understand what you're trying to get at...

// if title is set in html:
<title>test of compoundAlert</title>
// otherwise
document.title = "test of compoundAlert";
<script...

// globals are children of window
// except those specifically attached to document [window.document]

// some stuff to test:

var c = 123;
var str = "this is a string";
var f = function () {
var local = "test";
return local + " this";
}

//I'm gonna go out on a limb here -- just for grins:

function
myObj() {
this.prop = "property";
this.meth = function(arg)
{
return arg;
}
}

var o = new myObj();
// gonna need this to grab the object constructor's name:

function
getConstructor(o)
{
var s = new String(o.constructor);

// grab everything after 'function and before '('
var part = s.match(/function\s+([^\(]+)/);

var name = part ? part[1].replace(/ /g,"") : "function"; // see ** note

// the replace strips any unwanted spaces due to
// "coding style" of: function myObj ( arglist )...
return name;
}

/* ** note: if object is declared:

myObj = function() {...}

"myObj" will not be returned -- "function" will --
and the variable name will be used in compoundAlert
*/
function
compoundAlert()
{

var format = "";

for(var i = 0; i < arguments.length; i++)
{
var argname = arguments[i];
// test for document element otherwise use window
var parent = argname.indexOf("document.") != -1 ? document : window;

if(parent == document)
argname = argname.replace(/document\./,"");

var type = typeof(parent[argname]); // use associative indexing
var value = parent[argname];

format += "argument name: " + argname + "\n" +
"argument type: " + type + "\n" +
"value of argument:\n" + value + "\n\n";

// just for grins... a little lagniappe... expand objects...
if(type == "object")
{
var tmp = parent[argname];
var cnst = getConstructor(tmp); // const is reserved keyword
if(cnst == "function") // failsafe
cnst = argname;

format += "Object: " + cnst + "\n";

for(var a in tmp)
{
format += a + ": " + tmp[a] + "\n";
}
format += "\n";
}

}

alert(format);
}

compoundAlert('c','str','f','document.title', 'o');

// all must be passed as strings for varname = varvalue formatting
should get you started... Things like "Math" methods, etc... are not
covered here -- an exercise for you to work out (not that there's really
anything useful to get -- Math methods are native code and will display
'[native code]')
if you have any trouble running this, let me know -- i developed it on a
pc and hand-copied it over to a mac, made several revisions and patches
before sending...there might be typos.


Fox
****************

optimistx wrote:

How to write a function f(x) or f('x') so that it produces the same output
as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the variable
value one would save a lot of typing during one's lifetime.

I think there is so simple solution for this that I probable will feel very
embarrassed after getting the answer. So I blush in advance :).

Jul 23 '05 #12
rh
Richard Cornford wrote:
rh wrote:
<snip>
ALERT = eval; // Slip sheep's clothing on nasty wolf!

<snip>
Notes:

- Creating the ALERT reference to the built-in "eval" function
appears to work in IE 6 and Opera 7.11. It fails in Netscape/Mozilla
in that local execution context is not maintained (however, the above
works if eval is used without substitution).

<snip>

Failure should be expected in that context as ECMA 262 3rd ed. Section
15.1.2.1 ends:-

| If value of the eval property is used in any way other than
| a direct call (that is, other than by the explicit use of
| its name as an Identifier which is the MemberExpression in
| a CallExpression), or if the eval property is assigned to,
| an EvalError exception may be thrown.


But that doesn't include "may produce invalid or unintended results"
as an alternative. So, as I read it, failure should be anticipated
based on the possibility of an exception being thrown, but not
expected.

Where I would have expected an exception is on an assignment to eval.
Interestingly though :~/, all browsers mentioned above seem to be
quite willing to allow an assignment to eval without producing an
exception.

So basically, it seems your allowed to mess with eval if the browser
doesn't object. And should one decide to do so, Jackass TV is sure to
deny any responsibility for the consequences. :)

../rh
Jul 23 '05 #13
There is no good solution, but this is a funny one...

var a = "asd";
alertt( a );

function alertt ( value ) {
/alertt\(([^\)]*)\)/.test( alertt.caller );
alert( RegExp.$1 + " == " + value );
}

"optimistx" <op*************@hotmail.com> wrote in message news:<tR****************@reader1.news.jippii.net>. ..
How to write a function f(x) or f('x') so that it produces the same output
as a call to alert-function:

var x='abc';

alert('x='+x);

In testing one needs to write similar alert() calls often. By having a
function f(), which would add the variable name in front of the variable
value one would save a lot of typing during one's lifetime.

I think there is so simple solution for this that I probable will feel very
embarrassed after getting the answer. So I blush in advance :).

Jul 23 '05 #14
rh
mi**@n4te.com (Nathan Sweet) wrote in message news:<4f**************************@posting.google. com>...
There is no good solution, but this is a funny one...

var a = "asd";
alertt( a );

function alertt ( value ) {
/alertt\(([^\)]*)\)/.test( alertt.caller );
alert( RegExp.$1 + " == " + value );
}


Just to tickle yourself further, you might try:

function test(){
var a = "asd";
var b = "b";
alertt( b );
alertt( a );
}

Math.random could also used as a way to associate variable names with
incorrect values. It makes debugging a real riot. ;-)

Note that "caller" is deprecated as of JavaScript 1.3, and nonetheless
it has a null value by definition when the call is made from the
global environment ...

../rh
Jul 23 '05 #15
Bonjour à Nathan Sweet <mi**@n4te.com> qui nous a écrit :
There is no good solution, but this is a funny one...

var a = "asd";
alertt( a );

function alertt ( value ) {
/alertt\(([^\)]*)\)/.test( alertt.caller );
alert( RegExp.$1 + " == " + value );
}


For "global variables" :

foncAlert( s ) {
alert( s +" = "+ window[ s ] );
}

foncAlert( "nom_var" );

--
Cordialement, Thierry ;-)

Jul 23 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: schieco | last post by:
The following code always prints the debug lines inside the conditional if statement before and after the alert statement when the session has timed out, but the alert and redirect only appear/work...
4
by: hugo2 | last post by:
Most of these characters are not on the standard keyboard. Here's a successful contrivance, with comments & cautions, a little page that works in IE6. <HTML><HEAD><SCRIPT TYPE="text/javascript">...
11
by: Alistair Saldanha | last post by:
I'm looking for the event that is fired by Internet Explorer to an "alert": <SCRIPT> Alert("You already have a session open") </SCRIPT> The event would be webBrowser.Document.???? Much...
0
by: Stephanie | last post by:
I have a problem with an Alert that is supposed to invoke a Job. Here are some details: Windows Server 2000 SQL Server Standard Ed. ver. 8.00.818 (Sp3) Alert: SQL Server performance condition...
3
by: umdsasha | last post by:
So, basically, I need to detect whether an alert window was thrown. I can't find where it's thrown from but I need to disable a button only if there were no alert windows thrown. Any ideas? ...
4
by: joe | last post by:
Hi, I defined: <div id="abc"> </div> in my .html file, after an Ajax query my weberserver sends: <script language="JavaScript"> alert('Hello World!"); </script>
5
by: vjsv2007 | last post by:
Can you help to make one alert with all details? <script type="text/javascript"> <!-- function validate_form ( ) { valid = true;
24
by: Jeremy J Starcher | last post by:
While reading c.l.j, I've noticed that some people prefer and indeed even recommend the use of "window.alert()" over "alert()". I can't find any technical reason to make this distinction, and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.