www.webdeveloper.com
Results 1 to 3 of 3

Thread: [RESOLVED] Associative array problem, what if item is missing?

  1. #1
    Join Date
    Sep 2008
    Location
    Jackson MS
    Posts
    374

    resolved [RESOLVED] Associative array problem, what if item is missing?

    I have the following function in various related pages:
    Code:
    function getNoteLength(notelet) {  // Returns duration of note , whole = 768
    var NoteLengths = { "16th":48, "32nd":24, "4th":192, "64th":12, "8th":96, "Half":384, "Whole":768, "undefined":-1 }
    
    parts = notelet.split(",");
    var  noteLength= -1;
    noteLength = NoteLengths[parts[0]];
    
      for (var i = 1; i < parts.length; i++) {
        if (parts[i].substr(0,9) == "DblDotted") {
    	  noteLength = noteLength * 7 / 4; }
    	else
          if (parts[i].substr(0,6) == "Dotted") {
    	    noteLength = noteLength * 3 / 2; }
    	  else
    	    if (parts[i].substr(0,7) == "Triplet") {
    	      noteLength = noteLength * 2 / 3; } }
      return noteLength;
    }
    This is my first attempt at using associative arrays (I had been using a traditional search), but was wondering how to I test for a not found condition such as looking for "128th" or "4nd". I would like to return -1, but noteLength comes back as "undefined". The function receives a string such as "4th,Dotted,Slur" for example and would return 288.

    TIA

  2. #2
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Code:
    var noteLength = ( NoteLengths[parts[0]] === undefined ) ? -1 : NoteLengths[parts[0]];

  3. #3
    Join Date
    Sep 2008
    Location
    Jackson MS
    Posts
    374
    That's a lot more concise than what I ended up using
    Code:
    if (typeof(noteLength) == "undefined")
      return -1;
    Thanks for the input.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles