简体   繁体   English

在迭代对象数组时替换为for循环

[英]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. 我有一个for循环,该循环遍历对象数组,并为数组中的每个对象返回一个格式化对象的方法。

I was wondering if there's a better substitute for the for loop instead of 'forEach' I've used here. 我想知道是否有更好的替代for循环,而不是我在这里使用的'forEach'。 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. 注意:我已经在else条件中运行了这个循环。

It's probably quite easy to just pass formatObj to forEach : formatObj传递给forEach可能很容易:

arrItems.forEach(formatObj);

No return , no index handling, nothing. 没有return ,没有索引处理,什么都没有。

尝试这个

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. 在这种情况下,您应该知道JS对象是通过引用传递的,因此您可以在被调用函数中对其进行修改,并且它们也会在您的数组中进行更改。 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: 或者,因为forEach方法接受带有第一个参数作为项目的函数,所以您可以直接传递该函数:

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. 您使用的方法是用于迭代一系列项目的标准JS,并且根据运行您的代码的JS引擎, 必须以优化的方式实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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