HISE Logo Forum
    • Categories
    • Register
    • Login

    Check if array key exists via the in operator

    Scheduled Pinned Locked Moved Scripting
    3 Posts 2 Posters 637 Views
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • d.healeyD
      d.healey
      last edited by

      The in operator doesn't seem to be acting like I would expect. In this snippet of code it should be printing 0 but it always prints 1.

      var myObj = {pie:"apple", cake:"chocolate", sausage:"dog"};
      
      if ("fish" in myObj)
      {
      	Console.print(1);
      }
      else 
      {
      	Console.print(0);
      }

      Libre Wave - Freedom respecting instruments and effects
      My Patreon - HISE tutorials
      YouTube Channel - Public HISE tutorials

      1 Reply Last reply Reply Quote 0
      • Christoph HartC
        Christoph Hart
        last edited by

        Yeah, the in operator is only used for the iterator loop.

        But you can test if the key exists like this:

        var myObj = {"pie":"apple", "cake":"chocolate", "sausage":"dog"};
        
        inline function keyExists(obj, key)
        {
        	return !(obj[key] == void); // Important: not undefined!
        }
        
        if (keyExists(myObj, "fish"))
        {
        	Console.print(1);
        }
        else 
        {
        	Console.print(0);
        }
        
        1 Reply Last reply Reply Quote 0
        • d.healeyD
          d.healey
          last edited by

          Thank you :)

          Libre Wave - Freedom respecting instruments and effects
          My Patreon - HISE tutorials
          YouTube Channel - Public HISE tutorials

          1 Reply Last reply Reply Quote 0
          • First post
            Last post

          46

          Online

          1.7k

          Users

          11.7k

          Topics

          101.8k

          Posts