Chrome查找数组最大值时抛出TypeError,为何PythonTutor运行正常?
I wrote the following JavaScript code to find the maximum value in an array:
function max(input) { var maxNum = 0; for(var i = 0; i <= input.length; i++) { if(maxNum < input[i]) { maxNum = input[i]; } } return maxNum; } max([1, 2, 3, 7]);When I run this code in Google Chrome, Edge, or Firefox, I get an error:
max.js:20 Uncaught TypeError: Cannot read property 'length' of undefined at max (max.js:20) at <anonymous>:1:1. But when I run it in PythonTutor's JavaScript environment, it returns the correct result without syntax issues. Why is this happening?
Let's break this down step by step:
First, the root cause of the TypeError
The error Cannot read property 'length' of undefined tells us one clear thing: when you called the max function, you didn't pass any argument to it. That means the input parameter inside the function was undefined, and trying to access undefined.length throws that TypeError.
Why does PythonTutor work fine?
In PythonTutor, you're running the entire code block in one go—both the function definition and the call max([1,2,3,7]) where you pass the array as an argument. So input gets properly set to the array, and the function can read its length property without issues.
Why does this happen in browsers?
There are a few likely scenarios:
- Accidentally calling
max()without arguments: If you ran the function definition in the browser (via a script file or console), then later typedmax()(no array) in the console, you'd get this error. It's easy to mistype or forget the argument when testing interactively. - Execution order mix-up: If you tried calling
max([1,2,3,7])before defining the function (though function declarations are hoisted in JS, so this shouldn't usually cause this specific error—unless you used a function expression likeconst max = function() {...}instead of a declaration). - Global variable conflict: In rare cases, another script might have overwritten your
maxfunction with something else, but that's less likely unless you're working in a messy global scope.
Bonus: Fixing other bugs in your code
While the TypeError is the immediate issue, your code has another hidden bug that will fail for arrays with negative numbers (e.g., max([-5, -3]) would return 0 instead of -3). Here's a corrected version that handles edge cases properly:
function max(input) { // Guard clause for invalid inputs if (!Array.isArray(input) || input.length === 0) { return undefined; // Adjust this to your needs (e.g., return null or throw an error) } var maxNum = input[0]; // Initialize with the first element instead of 0 // Loop from the second element to avoid redundant checks for(var i = 1; i < input.length; i++) { if(maxNum < input[i]) { maxNum = input[i]; } } return maxNum; } // Test cases max([1, 2, 3, 7]); // Returns 7 max([-5, -3]); // Returns -3 max([]); // Returns undefined
内容的提问来源于stack exchange,提问作者NeoDicereCant

