alert('x='+x)

Discussion in 'Javascript' started by optimistx, Apr 5, 2004.

  1. optimistx

    optimistx Guest

    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 :).
    optimistx, Apr 5, 2004
    #1
    1. Advertising

  2. optimistx

    Evertjan. Guest

    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)
    Evertjan., Apr 5, 2004
    #2
    1. Advertising

  3. optimistx

    optimistx Guest

    "Evertjan." <> kirjoitti viestissä
    news:Xns94C26883C3332eejj99@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+'='+eval(arguments)+'\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?
    optimistx, Apr 5, 2004
    #3
  4. optimistx

    Evertjan. Guest

    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+' = '+window[arguments]+'\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)
    Evertjan., Apr 5, 2004
    #4
  5. optimistx wrote:
    <snip>
    > alertt=function(){
    > var s='';
    > for (var i=0;i<arguments.length;i=i+1){
    > s+=arguments+'='+eval(arguments)+'\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.
    Richard Cornford, Apr 5, 2004
    #5
  6. JRS: In article <tR6cc.1869$>, seen in
    news:comp.lang.javascript, optimistx <>
    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.
    Dr John Stockton, Apr 5, 2004
    #6
  7. optimistx

    Evertjan. Guest

    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.

    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;

    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
    Evertjan., Apr 5, 2004
    #7
  8. 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.
    Richard Cornford, Apr 5, 2004
    #8
  9. optimistx

    optimistx Guest

    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?
    optimistx, Apr 5, 2004
    #9
  10. optimistx

    rh Guest

    Dr John Stockton wrote:

    > optimistx <>
    > 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.javascript&hl=en&lr=&ie=UTF-8&group=comp.lang.javascript&scoring=d&selm=c4ehko01c6%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
    rh, Apr 6, 2004
    #10
  11. 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.
    Richard Cornford, Apr 6, 2004
    #11
  12. optimistx

    Fox Guest

    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;
    // 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 :).
    Fox, Apr 6, 2004
    #12
  13. optimistx

    rh Guest

    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
    rh, Apr 6, 2004
    #13
  14. optimistx

    Nathan Sweet Guest

    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" <> wrote in message news:<tR6cc.1869$>...
    > 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 :).
    Nathan Sweet, Apr 7, 2004
    #14
  15. optimistx

    rh Guest

    (Nathan Sweet) wrote in message news:<>...
    > 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
    rh, Apr 8, 2004
    #15
  16. optimistx

    Cenekemoi Guest

    Bonjour à Nathan Sweet <> 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 ;-)
    Cenekemoi, Apr 8, 2004
    #16
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Erik Veldkamp
    Replies:
    2
    Views:
    21,959
    rogachez
    Jun 18, 2010
  2. Joel Barsotti

    validation with alert pop ups

    Joel Barsotti, Aug 8, 2003, in forum: ASP .Net
    Replies:
    1
    Views:
    354
    Steve C. Orr, MCSD
    Aug 8, 2003
  3. Lauchlan M
    Replies:
    2
    Views:
    729
    Lauchlan M
    Aug 26, 2003
  4. Mersh
    Replies:
    0
    Views:
    484
    Mersh
    Mar 13, 2007
  5. Ganesh
    Replies:
    0
    Views:
    548
    Ganesh
    Jun 29, 2007
Loading...

Share This Page