任何人都可以向我解释以下给我。JavaScript和Jquery循环数组中的JavaScript构造函数
案例1:
function MyObj() {
this.myArray = new Array();
for(var i = 0; i<5; i++){
this.myArray.push(i);
console.log("add to array:" + i);
}
}
如我所料,其工作原理。 this.myArray有0,1,2,3,4。
案例2:
function MyObj() {
this.myArray = new Array();
$.each([0,1,2,3,4],function(i,v){
this.myArray.push(i);
console.log("add to array:" + v);
});
}
我从萤火虫抱怨 “this.myArray是不确定的。”
谢谢。
这是因为范围。情况2中的“this”是数组中的实际数字。它引用了[0,1,2,3,4]。你只需要创建一个var并且不要使用'this'。所以你可以做一些类似'function(){myres.push(this);' – Matt