可以使用for循环代替Array.forEach,或者在调用Array.forEach时使用箭头函数来避免this指向错误的问题。以下是示例代码:
//使用for循环代替Array.forEach const arr = [1, 2, 3]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
//使用箭头函数避免this指向错误 const obj = { vals: [1, 2, 3], logValues() { this.vals.forEach(val => { console.log(val); }); } };
obj.logValues(); //输出1, 2, 3