Javascript 如何从原型中的forEach推送到构造函数中的数组?

Javascript 如何从原型中的forEach推送到构造函数中的数组?,javascript,arrays,prototype,Javascript,Arrays,Prototype,如果我有一个这样的全局数组 var arr = [value1, value2...]; function myFunction() { this.array = []; this.toArray(); } myFunction.prototype.toArray = function() { arr.forEach(function() { if (statement) { // How can I do if I from here

如果我有一个这样的全局数组

var arr = [value1, value2...];
function myFunction() {
    this.array = [];
    this.toArray();
}
myFunction.prototype.toArray = function() {
    arr.forEach(function() {
        if (statement) {
        // How can I do if I from here, want to push the current value, to the array in the cunstructor function?
        }
    });
}
然后我找到了一个像这样的承包商

var arr = [value1, value2...];
function myFunction() {
    this.array = [];
    this.toArray();
}
myFunction.prototype.toArray = function() {
    arr.forEach(function() {
        if (statement) {
        // How can I do if I from here, want to push the current value, to the array in the cunstructor function?
        }
    });
}
然后是这样的原型方法

var arr = [value1, value2...];
function myFunction() {
    this.array = [];
    this.toArray();
}
myFunction.prototype.toArray = function() {
    arr.forEach(function() {
        if (statement) {
        // How can I do if I from here, want to push the current value, to the array in the cunstructor function?
        }
    });
}
正如注释所说,如果我从注释所在的位置开始,想要将forEach函数中的当前值推回到构造函数中的数组中吗?我尝试了
这个.array.push()但我意识到我不能使用它,因为它现在指的是arr数组。

编辑 如果您不喜欢上面代码段中的
var that=this
,您可以:

myFunction.prototype.toArray = function(arr) {
    arr.forEach((function(item) {
        if (item%2 ===0) {
           this.array.push(item);
        }
    }).bind(this));
}
但我更喜欢:
函数myFunction(){
this.array=[];
}
myFunction.prototype.toArray=函数(arr){
arr.forEach(功能(项目){
如果(项目%2==0){
this.array.push(item);
}
}).约束(这个);
}
var test=新的myFunction();
var-arr=[1,2,3,4];
测试。toArray(arr);
警报(test.array)编辑
如果您不喜欢上面代码段中的
var that=this
,您可以:

myFunction.prototype.toArray = function(arr) {
    arr.forEach((function(item) {
        if (item%2 ===0) {
           this.array.push(item);
        }
    }).bind(this));
}
但我更喜欢:
函数myFunction(){
this.array=[];
}
myFunction.prototype.toArray=函数(arr){
arr.forEach(功能(项目){
如果(项目%2==0){
this.array.push(item);
}
}).约束(这个);
}
var test=新的myFunction();
var-arr=[1,2,3,4];
测试。toArray(arr);

警报(test.array)
未引用对象。这就是问题所在,我无法使用未定义的推送。我怀疑这是因为this关键字现在引用的是arr数组,而不是myFunction的实例?@Alex抱歉我回答得太快了,我用正确的解决方案和一个片段编辑了我的答案,很好,谢谢!但是不使用它,难道不可能将this关键字作为参数/参数传递吗?@Alex:据我所知,它不是。您可以创建自己的forEach函数,但是有一个
var=this
是常见的,并且不是问题
没有引用对象。这就是问题所在,我无法使用未定义的推送。我怀疑这是因为this关键字现在引用的是arr数组,而不是myFunction的实例?@Alex抱歉我回答得太快了,我用正确的解决方案和一个片段编辑了我的答案,很好,谢谢!但是不使用它,难道不可能将this关键字作为参数/参数传递吗?@Alex:据我所知,它不是。您可以创建自己的forEach函数,但是有一个
var=this
是很常见的,这不是我建议的问题,尤其是第二个参数。