2011-12-28 260 views
1

在Javascript中,可以使用「in」運算符檢查數組中是否出現字符串?使用「in」檢查字符串中是否出現字符串

對於如:

var moveAnims = new Array("fly", "wipe", "flip", "cube"); 

    alert("wipe" in moveAnims); 
    alert("fly " in moveAnims); 
    alert("fly" in moveAnims); 
    alert("Cube" in moveAnims); 

或者是隻有這樣,才能做到這一點反覆?

var moveAnims = new Array("fly", "wipe", "flip", "cube"); 
var targets  = new Array("wipe", "fly ", "fly", "Cube"); 

for (var i=0; i<moveAnims.length; i++) 
{ 
    for (var j=0; j<targets.length; j++) 
     if (targets[j] == moveAnims[i]) 
      alert("Found "+targets[j]); 
} 
+0

看看http://stackoverflow.com/questions/237104/array-containsobj-in-javascript你的答案。 – 2011-12-28 21:47:29

+0

你不能使用'in'。這只是檢查具有給定名稱的a *屬性*是否存在於對象中。 – 2011-12-28 21:48:02

回答

2

您應該可以使用.indexOf()來獲取對象的位置。檢查它是否是-1以查看它是否不存在。

2

不,因爲in操作員檢查對象的,該對象在數組中是0, 1, 2, ...

您可以使用indexOf,但是:

if(~moveAnims.indexOf("fly")) { // ~ is a useful hack here (-1 if not found, and 
    // ...      // ~-1 === 0 and is the only falsy result of ~) 
} 

注意indexOf是不是在舊的瀏覽器可用,但也有墊片在那裏。

+1

'-1'的否定結果是通過實現來定義的。在所有系統上''**'可能不會等於二進制'1111 1111'。 OP應該檢查這個值是否等於'-1',如果要在幾個開發人員之間傳遞代碼,它將保證工作並且會減輕可讀性。 – 2011-12-28 21:51:57

+0

@refp:感謝您的注意,但我認爲這個公式只是'〜x === -x - 1',同樣在這裏指出(http://en.wikipedia.org/wiki/Bitwise_operation#NOT)。和' - -1 - 1 === 0'。 – pimvdb 2011-12-28 21:53:53

+0

IIRC ecma標準並不強制實施它的系統使用二進制補碼,即使不常見,也有其他系統可以表示負數。 OP可能(也可能會)使用你的方法是安全的,但它不是100%保證。 – 2011-12-28 21:58:07

1

嘗試indexOf

moveAnims.indexOf('string') 
相關問題