Javascript 为什么修改“Array.prototype”不';不行?

Javascript 为什么修改“Array.prototype”不';不行?,javascript,Javascript,请参阅- 我得到以下错误 类型错误:无法读取未定义的的属性'method1' 为什么会这样?如何修复此问题?对我来说很好,只添加了一个字符: Array.prototype.method1 = function() { console.log("method1 has been called"); }; [1,2,3,4].method1(); 您缺少一个分号: Array.prototype.method1 = function() { console.log("method

请参阅-

我得到以下错误

类型错误:无法读取
未定义的
的属性
'method1'


为什么会这样?如何修复此问题?

对我来说很好,只添加了一个字符:

Array.prototype.method1 = function() {
    console.log("method1 has been called");
};
[1,2,3,4].method1();

您缺少一个分号:

Array.prototype.method1 = function() {
    console.log("method1 called");
}; // <--- Hi there!
[1,2,3,4].method1();
小心分号

一些阅读材料:

  • 规格:

虽然
console.log([1,2,3,4].method1()),但您的代码工作正常打印出未定义的内容(在您的小提琴中),因为method1本身不返回任何字符串。您已经包含了您尝试过的内容,但没有包含您期望的内容或出错的内容。@gopalrao My bad。你的代码有一个真正的问题。你应该使用
在函数定义之后。JavaScript将
函数(){..}[1,2,3,4]
视为单个表达式。由于它返回未定义的
,您得到了错误。@ScottKaye这就是我道歉并投票重新打开的原因。请解释为什么这里需要“一个字符”。在控制台下运行时,您的代码是正确的。这个bug必须只属于JSFIDLE。将其与以下内容进行比较:@Beri当在控制台中逐个语句运行时,错误不在那里,因为数组不在那里,从而使js引擎误认为它是一个属性访问。
Array.prototype.method1 = function() {
    console.log("method1 called");
}; // <--- Hi there!
[1,2,3,4].method1();
Array.prototype.method1 = function() { ... }[1,2,3,4].method1();
// after evaluating the comma operator:
Array.prototype.method1 = function() { ... }[4].method1();
// naturally, functions don't have a fourth index
undefined.method1();
// Error :(