2015-04-30 37 views
0

这是行不通的吗?我认为这是有效的,但它不起作用。使用“in”检查字符串是否在数组中

var items = ["image", "text"]; 
console.log(this.type) 
if(this.type in items){ 
    console.log("here") 
} 

console.log(this.type)显示image,但here永远不会显示。

我做错了什么,或者我在想错误的语言?

+0

您必须指定索引号不是值。 – chRyNaN

回答

8

in检查对象的属性名称。

在这里,你需要的是indexOf

if (~items.indexOf(this.type)){ 

注:这是使用bitwise not operator

if (items.indexOf(this.type)!==-1){ 

一个短版。

+0

@GlenSwift我编辑来解释那点 –

+0

啊凉快!我想知道'〜'是什么意思! –

+0

我明白了,谢谢 –

0

你可以做

var items = ["image", "text"]; 
 
var item = "image"; 
 
if (items.indexOf(item) > -1) { 
 
    console.log("here"); 
 
}

Array.indexOf() MDN

0

的 “中的” 在JavaScript中的关键字仅适用于键和对象的属性。我会做的方式:

if (items.indexOf(this.type) !== -1) 

这将返回类型的索引你正在寻找或-1,如果它不存在。如果它不等于-1,那么它就在那里。

相关问题