当使用Array.forEach()方法时,可以在回调函数中添加三个参数,分别表示当前正在处理的元素、元素的索引和完整的数组。因此,在处理包含文本元素的数组时,可以通过检查元素类型来避免错误。
示例代码:
const arr = [1, 2, "text", 4, "more text"];
arr.forEach((element, index, array) => { if (typeof element === "number") { // 处理数字元素 console.log(element); } else { // 处理文本元素 console.log("文本元素:" + element); } });
// 输出: // 1 // 2 // 文本元素:text // 4 // 文本元素:more text