The use of in keyword in js

1. Check whether the object is an element/attribute of an array/object

When used alone, the in operator returns true if the given property is accessible through the object

// When the object is an array the variable refers to the index of the array
const arr=['a'.'b'.'c']   
console.log('a' in arr); //false
console.log(1 in arr); //true
 console.log(3 in arr);// false
Copy the code
// When an object is an object, variables refer to properties of the object
let obj={
    a:'one'.b:'two'.c:'three'
}
console.log(2 in obj); //false
console.log('b' in obj); //true
Copy the code

for… In circulation

For an array it loops out the elements of the array; What you loop out for objects are object properties

// loop array
const arr=['a'.'b'.'c']
for (let index in arr){
    console.log(arr[index]) //index represents the subscript
} // a b c
// Loop objects
let obj={
    a:'one'.b:'two'.c:'three'
}
for (let index in obj){
    console.log(obj[index])  //index represents the attribute name
}
// one two three


Copy the code