TypeError: cannot use 'in' operator to search for 'x' in 'y'

이 문서는 아직 자원 봉사자들이 한국어로 번역하지 않았습니다. 참여해서 번역을 마치도록 도와 주세요!
English (US)의 문서도 읽어보세요.

Message

TypeError: cannot use 'in' operator to search for 'x' in 'y' (Firefox, Chrome)

Error type

TypeError

What went wrong?

The in operator can only be used to check if a property is in an object. You can't search in strings, or in numbers, or other primitive types.

Examples

Searching in strings

Unlike in other programming languages (e.g. Python), you can't search in strings using the in operator.

"Hello" in "Hello World"; 
// TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World'

Instead you will need to use String.prototype.indexOf(), for example.

"Hello World".indexOf("Hello") !== -1; 
// true

The operand can't be null or undefined

Make sure the object your are inspecting isn't actually null or undefined.

var foo = null;
"bar" in foo;
// TypeError: cannot use 'in' operator to search for 'bar' in 'foo'

The in operator always expects an object.

var foo = { baz: "bar" };
"bar" in foo; // false

"PI" in Math; // true
"pi" in Math; // false

Searching in arrays

Be careful when using the in operator to search in Array objects. The in operator checks the index number, not the value at that index.

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
3 in trees; // true
"oak" in trees; // false

See also

문서 태그 및 공헌자

 이 페이지의 공헌자: fscholz
 최종 변경: fscholz,