hi,欢迎访问本站!
当前位置: 首页Web前端正文

javascript中的for...in循环详解

墨初 Web前端 109阅读

在javascript脚本中,for...in循环是一种遍历对象属性的语法。此语法会遍历对象的所有可枚举数据。

for...in语法如下

for (const property in obj) {
    if (obj.hasOwnProperty(property)) {
        // 执行代码
    }
}

obj:需要遍历的对象

property:当前遍历的对象属性

hasOwnProperty():内置方法,用于检查对象是否有特定的自有属性

for...in示例

示例1:

let arr = ['php','java','html'];
for(let index in arr){
    console.log(index); // 输出当前的属相
    console.log(arr[index]); // 通过属性获取元素值
}

示例2:

// hasOwnProperty() 方法只处理自身的属性
Array.prototype.sayHello = function(){
  console.log("Hello")
}
Array.prototype.str = 'world';
let arr = ['php','java','html'];
arr.id = 10;
for(let index in arr){
    if (arr.hasOwnProperty(index)) {
        console.log(index); // 输出当前的属相
        console.log(arr[index]); // 通过属性获取元素值
    }
}
// 可对上面两个的打印结果
console.log('=============================');
for(let index in arr){
    console.log(index); 
    console.log(arr[index]); 
}

示例3

// 这是一个对象的变量
const myObject = {
  name: 'mochu',
  age: 25,
  host:'https://www.73so.com'
};
for(let index in myObject){
    console.log(index);
}

ps:

1、for...in 循环专门遍历对象的属性

2、for...in 也会遍历对象原型号上的可枚举属性

3、hasOwnProperty()方法可以确保for...in只处理自己身的属性

声明:无特别说明,转载请标明本文来源!
相关推荐