该问题可能是因为传递的参数不是纯粹的数组对象,而是一个“类数组”对象。类数组是一个具有 length 属性和索引的对象,但不是真正的数组对象,不能使用数组方法。此时可以使用 Array.from() 或 spread operator(扩展运算符)将类数组转换为真正的数组对象,然后再将其传递给 map 函数。
代码示例:
const obj = { 0: "apple", 1: "banana", 2: "orange", length: 3 };
// 通过 Array.from() 转换为真正的数组对象 const arr1 = Array.from(obj).map(item => item + " is a fruit."); console.log(arr1); // ["apple is a fruit.", "banana is a fruit.", "orange is a fruit."]
// 通过扩展运算符转换为真正的数组对象 const arr2 = [...obj].map(item => item + " is a fruit."); console.log(arr2); // ["apple is a fruit.", "banana is a fruit.", "orange is a fruit."]
另一种可能的解决方法是,在调用 map 函数时,将数组对象传递给该函数的第二个参数。这个参数将被传递给回调函数作为第二个参数,可以使用此参数引用原始数组对象。
代码示例:
const fruits = ["apple", "banana", "orange"];
const arr3 = fruits.map((item, index, arr) => { console.log(arr === fruits); // true return item + " is a fruit."; });
console.log(arr3); // ["apple is a fruit.", "banana is a fruit.", "orange is a fruit."]