Using an if statement with the in operator
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 i开发者_Python百科n a time-critical area.
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
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.
精彩评论