Câu hỏi phỏng vấn Javascript
Câu hỏi

What language constructions do you use for iterating over object properties and array items?

Câu trả lời

To iterate over object properties and array items in JavaScript, several language constructs can be used, each with its own use cases and characteristics.

Iterating Over Object Properties

for...in Loop

The for...in loop is a traditional way to iterate over the enumerable properties of an object, including inherited enumerable properties. However, it's important to note that this loop will iterate over all enumerable properties, which may include those inherited from the prototype chain. To ensure that only the object's own properties are considered, it's common to use the hasOwnProperty() method in conjunction with the for...in loop[1][2][3].

Object.entries() and Object.keys()

Object.entries() returns an array of a given object's own enumerable string-keyed property [key, value] pairs, which can be iterated with array iteration methods like forEach(), for...of, or a standard for loop. Similarly, Object.keys() returns an array of a given object's own enumerable property names, which can be used to iterate over the values of the object[3].

Iterating Over Array Items

for Loop

A standard for loop can be used to iterate over array items by initializing an index variable, setting a condition for the loop to continue, and incrementing the index variable. This method provides a lot of control over the iteration process[4].

while Loop

A while loop can also be used for array iteration by initializing an index variable outside the loop and using the length of the array as the condition to continue the loop[4].

forEach() Method

The forEach() method executes a provided function once for each array element. It's a higher-order function that abstracts away the loop mechanics[4].

map() Method

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It's often used when you want to transform the elements of an array[4].

filter() Method

The filter() method creates a new array with all elements that pass the test implemented by the provided function. It's useful for conditional iteration[4].

reduce() Method

The reduce() method executes a reducer function on each ele...

junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What advantages are using arrow functions?

expert

Compare Async/Await and Generators usage to achive same functionality

expert

In JavaScript, why is the this operator inconsistent?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào