您可以使用forEach()在两个数组上进行并
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
array1.forEach((element, index) => {
console.log(`Element of array1: ${element}`);
console.log(`Element of array2 with the same index: ${array2[index]}`);
});
这将输出:
Element of array1: 1
Element of array2 with the same index: 4
Element of array1: 2
Element of array2 with the same index: 5
Element of array1: 3
Element of array2 with the same index: 6
在这个例子中,我们通过使用相同的索引号,同时遍历了两个数组。
可以使用 `for...in` 循环遍历多个对象,如下所示:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
for (let key in obj1) {
console.log(key + ': ' + obj1[key]);
}
for (let key in obj2) {
console.log(key + ': ' + obj2[key]);
}
也可以使用 `Object.assign()` 方法将多个对象合并成一个对象,然后再使用 `for...in` 循环进行遍历,如下所示:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = Object.assign({}, obj1, obj2);
for (let key in mergedObj) {
console.log(key + ': ' + mergedObj[key]);
}
如果需要同时遍历多个数组,可以使用 `for` 循环和 `Array.length` 属性,如下所示:
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
for (let i = 0; i < arr1.length && i < arr2.length; i++) {
console.log(arr1[i] + ': ' + arr2[i]);
}
注意要判断两个数组的长度,防止出现越界的情况。