Javascript 获取类型错误:无法设置属性';0';尝试添加到数组时的未定义值
我在学打字。在这次尝试中,我试图将一个数字数组从我创建的Web服务中获取到一个javascript数组中 我有以下Typescript类:Javascript 获取类型错误:无法设置属性';0';尝试添加到数组时的未定义值,javascript,json,web-services,asp.net-web-api,typescript,Javascript,Json,Web Services,Asp.net Web Api,Typescript,我在学打字。在这次尝试中,我试图将一个数字数组从我创建的Web服务中获取到一个javascript数组中 我有以下Typescript类: class GameMap2 { Grid: Uint8Array; width: number; height: number; constructor(height: number, width: number) { this.height = height; this.width = w
class GameMap2 {
Grid: Uint8Array;
width: number;
height: number;
constructor(height: number, width: number) {
this.height = height;
this.width = width;
this.Grid = new Uint8Array(height * width);
}
generateMap() {
alert("calling generate");
$.ajax({
url: "/api/Maps/" + this.width + "/" + this.height,
async: false,
dataType: 'json',
success: function(data) {
alert("Ajax success");
for (var idx = 0; idx < data.length; idx++) {
this.Grid[idx] = data[idx];
}
}
});
}
}
类游戏地图2{
网格:uint8阵列;
宽度:数字;
高度:数字;
建造师(高度:编号,宽度:编号){
高度=高度;
这个。宽度=宽度;
this.Grid=新的UINT8阵列(高度*宽度);
}
generateMap(){
警报(“调用生成”);
$.ajax({
url:“/api/Maps/”+this.width+“/”+this.height,
async:false,
数据类型:“json”,
成功:功能(数据){
警报(“Ajax成功”);
对于(var idx=0;idx
从Web服务中,我将得到如下内容:[1,1,1,1,1,1,1,1,0,0,0,1,1,0,1,1,1,0,1,0,1,1,1,1,1,0,0,0,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1]
现在,当我尝试循环这个结果并将其放入网格数组时,我得到了错误:
TypeError:无法设置未定义的属性“0”
如果我将其更改为This.Grid.Push(data[idx])代码>我得到未定义的错误。
在我看来,我的网格数组实际上不在ajax回调的范围之内。这真的是真的吗?还是我做错了什么?
是否有其他方法可以将数组放入javascript数组?这是因为此
已更改成功回调中的上下文。请参考此
,并改用它:
generateMap() {
alert("calling generate");
var _this = this;
$.ajax({
url: "/api/Maps/" + this.width + "/" + this.height,
async: false,
dataType: 'json',
success: function(data) {
alert("Ajax success");
for (var idx = 0; idx < data.length; idx++) {
_this.Grid[idx] = data[idx];
}
}
});
}
generateMap(){
警报(“调用生成”);
var_this=这个;
$.ajax({
url:“/api/Maps/”+this.width+“/”+this.height,
async:false,
数据类型:“json”,
成功:功能(数据){
警报(“Ajax成功”);
对于(var idx=0;idx
事实上,这个问题是通过TypeScript直接解决的。该功能称为箭头函数
,它会像这样更改您的代码定义
class GameMap2 {
...
constructor(height: number, width: number) { ... }
generateMap() {
alert("calling generate");
$.ajax({
// instead of this
// success: function(data) {
// use this style, and the compiler will do the magic
// of keeping correct "this" for us
success: (data) => {
alert("Ajax success");
for (var idx = 0; idx < data.length; idx++) {
this.Grid[idx] = data[idx];
}
}
....
class GameMap2{
...
构造函数(高度:数字,宽度:数字){…}
generateMap(){
警报(“调用生成”);
$.ajax({
//而不是这个
//成功:功能(数据){
//使用这种风格,编译器将发挥神奇的作用
//为我们保持正确的“这个”
成功:(数据)=>{
警报(“Ajax成功”);
对于(var idx=0;idx
参见(小引用)
…“箭头函数表达式是函数表达式的一种紧凑形式,它省略了function关键字,并具有此关键字的词法范围。”基本上,Arrow函数帮助您自动保留某个范围。如果您查看编译器输出的代码,它只会创建一个var _this=this;并在函数内部使用
这是
这个
和那个
约定。下面的问题:说明为什么和如何使用它。我使用\u这个
是因为我选择了这个编码约定。这个
: