alert('x='+x)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • optimistx

    #1

    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 :).


  • Evertjan.

    #2
    Re: alert('x='+x)

    optimistx wrote on 05 apr 2004 in comp.lang.javas cript:
    [color=blue]
    > 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.
    >[/color]

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

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

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

    Comment

    • optimistx

      #3
      Re: alert('x='+x)


      "Evertjan." <exjxw.hannivoo rt@interxnl.net > kirjoitti viestissä
      news:Xns94C2688 3C3332eejj99@19 4.109.133.29...[color=blue]
      > optimistx wrote on 05 apr 2004 in comp.lang.javas cript:
      >[color=green]
      > > 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.
      > >[/color]
      >
      > function toAlert(x){
      > alert('toAlertP arameter = "'+x+'"');
      > }
      >
      > toAlert('Try me out')
      > toAlert( 355/113)
      >
      > --
      > Evertjan.
      > The Netherlands.
      > (Please change the x'es to dots in my emailaddress)[/color]

      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(argum ents[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?




      Comment

      • Evertjan.

        #4
        Re: alert('x='+x)

        optimistx wrote on 05 apr 2004 in comp.lang.javas cript:[color=blue]
        > By the way, is there a way to avoid eval() above?[/color]

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

        toAlert=functio n(){
        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)

        Comment

        • Richard Cornford

          #5
          Re: alert('x='+x)

          optimistx wrote:
          <snip>[color=blue]
          > alertt=function (){
          > var s='';
          > for (var i=0;i<arguments .length;i=i+1){
          > s+=arguments[i]+'='+eval(argum ents[i])+'\n';
          > }
          > alert(s);
          > }[/color]
          <snip>[color=blue]
          > Sorry to bother readers perhaps in vain. Hopefully the code is useful
          > for someone else except me :).[/color]

          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.


          Comment

          • Richard Cornford

            #6
            Re: alert('x='+x)

            Evertjan. wrote:[color=blue]
            > Richard Cornford wrote on 05 apr 2004 in comp.lang.javas cript:[color=green]
            >> The code is unlikely to be of that much use to you either.[/color]
            >
            > 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.[/color]

            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.
            [color=blue]
            > 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;[/color]

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

            Richard.


            Comment

            • optimistx

              #7
              Re: alert('x='+x)

              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?


              Comment

              • Dr John Stockton

                #8
                Re: alert('x='+x)

                JRS: In article <tR6cc.1869$YQ1 .796@reader1.ne ws.jippii.net>, seen in
                news:comp.lang. javascript, optimistx <optimistxPoist a@hotmail.com>
                posted at Mon, 5 Apr 2004 09:17:18 :
                [color=blue]
                >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.[/color]

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

                function f(x) { alert(x+'='+eva l(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+'="'+ev al(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.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                Comment

                • Robert

                  #9
                  Re: alert('x='+x)

                  In article <tR6cc.1869$YQ1 .796@reader1.ne ws.jippii.net>,
                  "optimistx" <optimistxPoist a@hotmail.com> wrote:

                  [color=blue]
                  > 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.[/color]

                  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.e arthlink.net

                  Robert

                  Comment

                  • rh

                    #10
                    Re: alert('x='+x)

                    Dr John Stockton wrote:
                    [color=blue]
                    > optimistx <optimistxPoist a@hotmail.com>
                    > posted at Mon, 5 Apr 2004 09:17:18 :
                    >[color=green]
                    > >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.[/color]
                    >
                    > It cannot be done with f(x), as the name is not then passed. But
                    >
                    > function f(x) { alert(x+'='+eva l(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+'="'+ev al(x)+'"') }
                    >[/color]

                    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"+var List[k]+ ": '"
                    +"+ (( typeof "+varList[k]+" == 'object') ? Dumper("+varLis t[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.c a/groups?q=%22mat t+kruse%22++gro up:comp.lang.ja vascript&hl=en& lr=&ie=UTF-8&group=comp.la ng.javascript&s coring=d&selm=c 4ehko01c6%40ene ws2.newsguy.com &rnum=7>

                    - It appears that the line

                    DumperTagProper ties["OPTION"] = ['text','value', 'defaultSelecte d'];

                    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);.
                    ___________
                    [color=blue]
                    > There is a way, I suspect, of doing it without eval.[/color]

                    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

                    Comment

                    • Richard Cornford

                      #11
                      Re: alert('x='+x)

                      rh wrote:
                      <snip>[color=blue]
                      > ALERT = eval; // Slip sheep's clothing on nasty wolf![/color]
                      <snip>[color=blue]
                      > 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).[/color]
                      <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 MemberExpressio n in
                      | a CallExpression) , or if the eval property is assigned to,
                      | an EvalError exception may be thrown.

                      Richard.


                      Comment

                      • Fox

                        #12
                        Re: alert('x='+x)

                        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.constr uctor);

                        // 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.lengt h; 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','d ocument.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:[color=blue]
                        >
                        > 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 :).[/color]

                        Comment

                        • rh

                          #13
                          Re: alert('x='+x)

                          Richard Cornford wrote:[color=blue]
                          > rh wrote:
                          > <snip>[color=green]
                          > > ALERT = eval; // Slip sheep's clothing on nasty wolf![/color]
                          > <snip>[color=green]
                          > > 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).[/color]
                          > <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 MemberExpressio n in
                          > | a CallExpression) , or if the eval property is assigned to,
                          > | an EvalError exception may be thrown.
                          >[/color]

                          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

                          Comment

                          • Nathan Sweet

                            #14
                            Re: alert('x='+x)

                            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" <optimistxPoist a@hotmail.com> wrote in message news:<tR6cc.186 9$YQ1.796@reade r1.news.jippii. net>...[color=blue]
                            > 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 :).[/color]

                            Comment

                            • rh

                              #15
                              Re: alert('x='+x)

                              misc@n4te.com (Nathan Sweet) wrote in message news:<4f028e5e. 0404071311.4ccf 3004@posting.go ogle.com>...[color=blue]
                              > 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 );
                              > }
                              >[/color]

                              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

                              Comment

                              Working...