例如,使用与之前相同的 person 对象,您可以使用 Object.entries() 方法,如下所示: //1. Using afor() loopfor(letindex=0;index< entries.length;index++) {}// Output: ["name","John"], ["age",30], ["favoriteColors", ["Red","...
The For/In LoopThe JavaScript for/in statement loops through the properties of an object:Example var person = {fname:"John", lname:"Doe", age:25}; var text = "";var x;for (x in person) { text += person[x]; } Try it yourself » The While Loop...
对象(Object):一种无序的键值对集合。 数组(Array):一种有序的集合,可以通过索引访问元素。 循环(Loop):重复执行一段代码直到满足某个条件。 遍历方法 1.for循环 优势:简单直观,适用于所有版本的JavaScript。类型:基本循环结构。应用场景:适用于需要精确控制循环次数或需要访问数组索引的场景。
// Object中使用for...of语句(方式1) for(letkeyofObject.keys(obj)){ console.log(`${key}:\t`, obj[key]); } // Object中使用for...of语句(方式1) for(letvalueofObject.values(obj)){ console.log(value); } // Object中使用for...of语句(方式2) for(let[key, value]ofObject.entries(ob...
方法2:使用 Object.values() 循环对象值 Object.values() 为我们提供了一个包含对象所有值的数组。您可以循环数组并轻松获取值。例如,看看这个 person 对象。您可以像这样使用 Object.values() : 复制 // Output: ["John", 40, ["Red", "Green"]]// 1. Using a for() loopfor(letindex=0;index<valu...
在前端开发过程中,我们经常使用到JavaScript 提供了很多种循环和迭代的方法,常见for, for…of, for…in, while, Array.forEach, 以及 Array.* (还有一些 Arra...
for - loops through a block of code a number of times for/in - loops through the properties of an object for/of - loops through the values of an iterable object while - loops through a block of code while a specified condition is true do/while - also loops through a block of code...
Using thefor...inloop, we can easily access each of the property names. // Print property names of objectfor(attributeinshark){console.log(attribute);} Copy Output species color numberOfTeeth We can also access the values of each property by using the property name as the index value of...
for-in语句 一般会使用for-in来遍历对象的属性的,不过属性需要enumerable才能被读取到。 for-in循环只遍历可枚举属性。一般常用来遍历对象,包括非整数类型的名称和继承的那些原型链上面的属性也能被遍历。像 Array和 Object使用内置构造函数所创建的对象都会继承自Objec...
for (let i = 0; i < array.length; i++) { console.log(array[i]); } 这段代码会打印数组中的每个元素。这里的条件表达式i < array.length确保了循环不会越界访问数组。 遍历对象属性 尽管for循环通常与数组一起使用,但它们也可以用来遍历JavaScript对象的属性。这需要配合使用Object.keys()或Object.entri...