2011-07-27 47 views
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. 

好吧,所以繼承人:我正在編寫一些需要根據文件類型選擇html的東西。 有沒有辦法實現(imageFormats中的srcType)?這不起作用。我需要一個for循環嗎?我總是可以在html中使用或者是,但是當我們添加格式時,這將是詳盡無遺的。 我不喜歡for循環的原因是它在時間關鍵區域使用寶貴的時間。在in運算符中使用if語句

回答

1

'in'操作僅對對象的屬性起作用,而不是數組的值。我想你想indexOf(srcType),如果找不到,返回-1,或者找到索引。

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 
+0

謝謝!我只是將數組放入一個對象中,工作正常:D –

0

您可以在Array對象上使用indexOf。有關JavaScript庫中可用選項的詳細信息,請參閱this question

indexOf可從JavaScript 1.6(ECMAScript第5版)獲得,並且MDC頁面中舊版瀏覽器有一個後備鏈接。

我不喜歡for循環的原因是它在時間關鍵區域使用了寶貴的時間。

您將不得不提供更多細節。一個簡單的循環不會花費太多時間,並且您擁有的只是數組中的一組三個元素。即使這個潛力變爲50或100,for循環也不應該成爲問題。另外,如果你可以給出你在做什麼(以及什麼時候)的意圖,你可能會得到更好的答案。

+0

感謝您的幫助。我不想使用它的原因是B/C,它必須運行這個過程數百次,並且會變得遲緩。 馬特回答我所需要的:) –