在 TypeScript 中使用索引遍历数组
使用 forEach() 方法迭代具有索引的数组,例如 arr.forEach((element, index) => {})。 回调函数采用的第二个参数是数组中元素的索引。
const arr: string[] = ['one', 'two', 'three'];
arr.forEach((element, index) => {
// ?️ one 0, two 1, three 2
console.log(element, index);
});
我们传递给 Array.forEach 方法的函数会针对数组中的每个元素进行调用。
回调函数传递以下 3 个参数:
- 数组中的当前元素。
- 数组中元素的索引。
- 我们调用 forEach() 方法的数组。
forEach 方法返回 undefined,因此它用于改变外部变量。
如果我们需要使用索引遍历数组,但每次迭代都返回一个值,请改用 Array.map 方法。
const arr: string[] = ['one', 'two', 'three'];
const result = arr.map((element, index) => {
return element + index;
});
// ?️ ['one0', 'two1', 'three2']
console.log(result);
我们传递给 map() 方法的函数会调用数组中的每个元素,并传递与 forEach() 相同的参数。
如果在满足条件时必须使用 break 关键字跳出循环,请改用基本的 for 循环。
const arr: string[] = ['one', 'two', 'three'];
for (let index = 0; index < arr.length; index++) {
// ?️ one 0, two 1
console.log(arr[index], index);
if (index === 1) {
break;
}
}
基本的 for 循环并不像使用 forEach() 那样优雅,但使我们能够使用 break 关键字在满足条件时跳出循环。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。