Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Array.prototype中的新函数无权访问此_Javascript_Arrays_Prototype - Fatal编程技术网

Javascript Array.prototype中的新函数无权访问此

Javascript Array.prototype中的新函数无权访问此,javascript,arrays,prototype,Javascript,Arrays,Prototype,目前,我正在为几次前端工作面试疯狂学习。我确实经历了一系列的问题,我现在被困在一个根本不难解决的问题上,但由于某种原因,我无法让它工作。也许你们可以看看: 问题是:向数组原型添加一个打印函数,用于打印数组中的所有内容。例如[1,2]。打印()->1,2 我自信地编写了这个函数,知道它会工作,但它没有: Array.prototype.print = () => { let str = '' for(let i = 0; i < this.length; i++) { t

目前,我正在为几次前端工作面试疯狂学习。我确实经历了一系列的问题,我现在被困在一个根本不难解决的问题上,但由于某种原因,我无法让它工作。也许你们可以看看:

问题是:向数组原型添加一个打印函数,用于打印数组中的所有内容。例如[1,2]。打印()->1,2

我自信地编写了这个函数,知道它会工作,但它没有:

Array.prototype.print = () => {
 let str = ''
 for(let i = 0; i < this.length; i++) {
     this[i+1] === undefined ? str += this[i] : str += `${this[i]}, `
 }
 return str
}
console.log([1,2].print())
Array.prototype.print=()=>{
设str=''
for(设i=0;i
当我运行这个函数时,我没有得到任何回报。我的想法是,
这个
应该与我正在研究的数组相关联,但事实并非如此。它被绑在窗户上

知道我做错了什么吗?我们将不胜感激

最好的,
Ayaz

使用箭头函数将外部作用域绑定到
,而不是在
数组的上下文中。prototype

Array.prototype.print=function(){
设str='';
设i=0;
设size=this.length;
如果(大小==1){
返回此[0];
}
对于(;iconsole.log([1,2,3].print())
使用箭头函数将外部作用域绑定到
,而不是在
数组的上下文中。prototype

Array.prototype.print=function(){
设str='';
设i=0;
设size=this.length;
如果(大小==1){
返回此[0];
}
对于(;iconsole.log([1,2,3].print())
箭头函数不会为
获取自己的值。而不是:

() => {
写:

function() {

对于
,箭头函数没有自己的值。而不是:

() => {
写:

function() {

不要使用arrow函数。arrow函数使用其封闭上下文的
this
,在本例中为
窗口
。使用普通函数,使用
函数
关键字,而不是箭头函数。明白了,非常感谢!的可能重复项不使用arrow函数。arrow函数获取其封闭上下文的
this
,在本例中为
window
。使用普通函数,使用
函数
关键字,而不是箭头函数。明白了,非常感谢!可能重复的