简体   繁体   中英

Substitute for for loop while iterating over an array of objects

I've a for loop which iterates over an array of objects and for each object in the array it returns a method which formats the object.

I was wondering if there's a better substitute for the for loop instead of 'forEach' I've used here. Could you please suggest something?

Here's the code:

for (var index = 0; index < arrItems.length; index++) {
  return formatObj(arrItems[index]);
}

forEach substitue:

var formattedObj;
arrItems.forEach(function (item) {
  formattedObj = formatObj(item);
});
return formattedObj;

Note: I've this loop running inside an else condition.

It's probably quite easy to just pass formatObj to forEach :

arrItems.forEach(formatObj);

No return , no index handling, nothing.

尝试这个

formattedObj = arrItems.map(fo=>formatObj(fo))

This code:

for (var index = 0; index < arrItems.length; index++) {
  return formatObj(arrItems[index]);
}

Will return the result of formatting the first object in your array.

This code:

var formattedObj;
arrItems.forEach(function (item) {
  formattedObj = formatObj(item);
});
return formattedObj;

Will return the result of formatting the last object in your array.

Are you trying to format your array in-place?

In that case you should know that JS objects are passed by reference, so you can modify them in the callee function, and they will be changed in your array too. So your code can change to:

arrItems.forEach(item => formatObj(item));
return arrItems;

Or, because the forEach method accepts a function with the first argument as the item, you can directly pass that function:

arrItems.forEach(formatObj);
return arrItems;

"Better" is a very subjective term. Better in what sense?

The method used by you is standard JS for iterating over an array of items, and depending on the JS engine running your code, it must be implemented in an optimised way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM