修复 JavaScript 中“无法读取 Undefined 的修复属性‘push’”错误的 4 种方法 了解如何轻松修复 JavaScript 中的“无法读取未定义的属性‘push’”错误。 当您尝试对旨在包含数组但实际上包含未定义值的错误变量调用 push() 方法时,会出现 JavaScript 中的修复“无法读取未定义的属性‘push’”错误。 这可能是错误由多种原因引起的: 我们将在本文中探讨所有这些可能原因的修复实用解决方案。 要修复“无法读取未定义的修复属性‘push’”错误,请确保变量在调用 push() 方法之前已使用数组初始化。错误 let doubles;let nums = [1,修复 2, 3, 4, 5];for (const num of nums) { let double = num * 2; // ❌ TypeError: cannot read properties of undefined (reading push) doubles.push(double); 在上面的例子中,我们在 doubles 变量上调用了 push() 方法,错误而没有先初始化它。修复 因为未初始化的变量在 JavaScript 中具有 undefined 的默认值,服务器托管所以调用 push() 会引发错误。 要修复该错误,我们所要做的就是将 doubles 变量分配给一个数组(对于我们的用例来说是空的): // ✅ "doubles" initialized before use let doubles = [];let nums = [1, 2, 3, 4, 5];for (const num of nums) { let double = num * 2; // ✅ push() called - no error thrown doubles.push(double); 要修复“无法读取未定义的属性‘push’”错误,请确保在调用 push() 之前没有从数组变量中访问元素,而是在实际数组变量上调用 push()。 const array = [];// ❌ TypeError: Cannot read properties of undefined (reading push) array[0].push(html); array[0].push(css); 使用括号索引访问 0 属性为我们提供了数组索引 0 处的元素。 该数组没有元素,因此 arr[0] 的计算结果为 undefined 并对其调用 push() 会导致错误。 为了解决这个问题,我们需要在数组变量上调用 push,而不是它的元素之一。 const array = [];// ✅ Call push() on "array" variable, not "array[0]" array.push(html); array.push(css); 要修复“无法读取未定义的属性‘push’”错误,请确保最后分配给变量的值不是未定义的。 let arr = [orange];arr.push(watermelon);arr = undefined;// hundreds of lines of code...// ❌ TypeError: Cannot read properties of undefined (reading push) 这里的问题是网站模板我们曾经明确地将变量设置为未定义,但后来我们在变量上调用了 push()。 对此的修复将根据您的情况而有所不同。 也许您在再次使用之前忘记将变量设置为定义的值: let arr = [orange];arr.push(watermelon);// ✅ Fixed: variable re-assigned 或者,也许你犯了一个错误,根本不打算将变量分配给 undefined: 要修复 JavaScript 中的“无法读取未定义的属性‘push’”错误,请确保调用 push() 方法的对象属性存在且未定义。 const students = [ { name: Mac, scores: [80, 85] }, { name: Robert }, { name: Michael, scores: [90, 70] }, ];// ❌ TypeError: Cannot read properties of undefined (reading push) 在这种情况下,出现错误是因为索引 1 处的对象元素没有 score 属性。 从对象访问不存在的属性不会在 JavaScript 中引发错误,而是会为您提供 undefined 值。 如果您尝试在该不存在的属性上调用类似 push() 的方法,您将遇到错误。 在这种情况下,我们可以通过将第二个数组元素的 score 属性设置为定义的值来修复错误。 const students = [ { name: Mac, scores: [80, 85] }, // ✅ Fixed: "scores" set to a defined value { name: Robert, scores: [] }, { name: Michael, scores: [90, 70] }, ];// ✅ "scores" property exists, "push()" works - no error thrown