js中in关键字的使用
1.判断对象是否是数组/对象的元素/属性
in在单独使用时 in操作符会在通过对象能够访问给定属性时返回true
//当对象是数组时 变量指的是数组的索引
const arr=['a','b','c']
console.log('a' in arr); //false
console.log(1 in arr); //true
console.log(3 in arr);// false
复制代码
// 当对象是对象时 变量指的是对象的属性
let obj={
a:'one',
b:'two',
c:'three'
}
console.log(2 in obj); //false
console.log('b' in obj); //true
复制代码
for…in循环
对于数组循环出来的是数组元素;对于对象循环出来的是对象属性
// 循环数组
const arr=['a','b','c']
for (let index in arr){
console.log(arr[index]) //index代表下标
} // a b c
// 循环对象
let obj={
a:'one',
b:'two',
c:'three'
}
for (let index in obj){
console.log(obj[index]) //index代表属性名
}
// one two three
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END