JavaScript中为Array做猴子补丁实现uniq()方法报错返回undefined的原因及基础概念解惑
Hey Noah, let's break down what's going wrong here and fill in those missing JS basics:
1. 致命的拼写错误(直接导致TypeError)
First off, the big one: you wrote Array.proptype.uniq instead of Array.prototype.uniq.
*Array.prototype* is the prototype object that all array instances inherit from—this is how you add methods that every array can use. Since Array.proptype doesn't exist (it's a typo), trying to set the *uniq* property on it throws that Cannot set properties of undefined error. This means your method never actually gets attached to arrays at all, so any attempt to call .uniq() later would fail (though in your case, the script crashes at this line before even getting to the console.log).
2. 未声明的变量(隐式全局污染)
In your function, narr = []; doesn't use *let* or *const* to declare the variable. In non-strict mode, this creates a global variable narr (which can cause weird bugs later if other code uses the same variable name), and in strict mode this would throw an error immediately. Always declare your variables with *const* (if the value won't change) or *let* (if it will):
const narr = [];
3. 关于forEach的误解
You mentioned thinking the forEach loop wasn't running—and you're right, but only because the typo stopped your method from being added in the first place. Fix the prototype spelling, and your loop logic actually works fine! Though for a more concise and efficient implementation, you could use JavaScript's *Set* object (which automatically stores unique values):
Array.prototype.uniq = function() { return [...new Set(this)]; };
基础概念你可能需要巩固
- Prototype Chain & Prototype Objects: JavaScript uses prototypes to share functionality across objects. All arrays are instances of
*Array*, so modifying*Array.prototype*adds methods to every array. Mixing up the name here shows you need to spend a bit more time with how prototypal inheritance works in JS. - Variable Declaration: Never leave variables undeclared.
*let*/*const*block-scoped variables are standard now—they prevent global pollution and make your code more predictable. - Strict Mode: Adding
'use strict';at the top of your script will catch mistakes like undeclared variables early, before they cause hard-to-debug issues. It's a great habit to get into.
内容的提问来源于stack exchange,提问作者noah_chazzan




