0
var srcType = source.slice(source.lastIndexOf('.'));
//srcType = fileExtension
var imageFormats = ['.jpg','.png','.gif'],
videoFormats = ['.ogv','.png','.gif'];
// two lists, acceptable video/image types
var htmlSting = ''; / /initialize the htmlstring

if (srcType in imageFormats) //heres where my question is!!!
    htmlString = '<img class="empty" id="it" src="'+source+'"> </img>';
else
    htmlString = '<video class="empty" id="it" src="'+source+'" controls> </img>';
// these statements choose the proper media type.

Ok, so heres the deal: I am coding something that needs to choose html based on a filetype. is there a way to achieve the (srcType in imageFormats)? This doesn't work. Do I need a for loop? I could always use or's in the html, but that would be exhaustive as we add formats. Reason I don't like a for loop is that it uses precious time in a time-critical area.

Jeremy Rubin
  • 567
  • 1
  • 7
  • 13

2 Answers2

1

The 'in' operation works only over the properties of an object, not the values of an array. I think you want indexOf(srcType), which returns -1 if not found, or the index if found.

imageFormats.indexOf('.jpg'); // => 0
imageFormats.indexOf('.foo'); // => -1

if(imageFormats.indexOf(srcType)){ }

var obj = {a: 1};
if('a' in obj){ } // evaluates to true
if('b' in obj){ } // evaluates to false
Matt
  • 41,216
  • 30
  • 109
  • 147
0

You can use indexOf on an Array object. See this question for details on options available in javascript libraries.

indexOf is available from JavaScript 1.6 (ECMAScript 5th Edition) and there is a fallback for older browsers in the MDC page linked.

Reason I don't like a for loop is that it uses precious time in a time-critical area.

You will have to give more details. A simple loop will not take much time, and all you have is a set of three elements in the array. Even with the potential of this becoming 50 or 100, the for loop should not be much of a problem.

Also, If you can give the intention of what you are doing (and when), you might get better answers.

Community
  • 1
  • 1
Nivas
  • 18,126
  • 4
  • 62
  • 76
  • Thank you for helping. The reason I don't want to use for is b/c it has to run the process hundreds of times and would get laggy. Matt answered with what I needed :) – Jeremy Rubin Jul 27 '11 at 15:51