in operator: (?in?) The first parameter is a string or other types that can be converted, the 2 parameter is an operation object or an array, and the value of the first operand is the attribute name of the second operand.
example
<!-- <script type="text/javascript">
function FF() {
this.age = 11;
}
FF.prototype.name = "kevin";
// in is used to determine whether the attribute exists in the object
var flag1 = "age" in new FF()? "Existing": "Not Existing";
var flag2 = "name" in new FF()? "Exist": "Not Exist";
alert(flag1)
alert(flag2)
</script> -->
<script type="text/javascript">
var key=new Array('java','javascrit','html')
var str = 'java';
if( 1 in key){
alert('This exists in this array')
}else(
alert('not inside')
)
</script>
Instructions:
1. Judgment
x in arr Here we should pay attention to the fact that when judging the array, x means the subscript. This consciousness is that there is an element with the subscript x in the arr array
x in obj The current x represents the attribute of the object, which means whether there is an attribute of x in obj
Sample code:
-
var arr = [1,4,6,'a'];
-
console.log('a' in arr);
-
console.log(4 in arr);
-
console.log(3 in arr);
The result of this output is: false false true;
Explanation: The first false, because the subscript cannot be a; the second false, because the length of the arr array is 4, the subscript is 0, 1, 2, 3 without subscript 4; the third is true, the reason Same as the second one
Sample code:
-
var obj = {a:3,b:'b',c:'4'}
-
console.log('a' in obj)
-
console.log('b' in obj)
-
console.log('4' in obj)
The output result is: true, true, false
Explanation: The first one is true because there is attribute a in obj; the second one is true because there is attribute b in obj, not because the value is b, which is why the third one is false
2. ...in... traverse arrays or objects
Traverse the array code:
-
var arr = [1,2,3,4,5,6,7]
-
for(var x in arr){
-
console.log(arr[x])
-
}
The output result is: 1 2 3 4 5 6 7
Traverse the object code:
-
var obj = {a:1,b:'c',d:3}
-
for(var x in obj){
-
console.log(obj[x])
-
}
The output result is: 1 c 3