TypeScript:在表中获取值时的未定义值

时间:2017-08-18 06:37:48

标签: angular typescript

如何在typeScript中获取表的值? Result of console.log(jsonUsers)

myComponent.ts:

let jsonUsers = [];
getUser() {

// When I do this console ==> I get response on the picture
 console.log(this.jsonUsers );

// Now I want to get value of code and label but it is not worked 
 console.log(jsonUsers.length); // ==> 0
 for (var index = 0; index < this.jsonUsers .length; index++) {
      var element = this.jsonUsers [0];
      console.log(element.code);
 }

MyCode

1 个答案:

答案 0 :(得分:0)

看起来那个数组上没有元素,你在控制台输出中看到的那些是对象的键。尝试这样的事情,让我们知道你看到了什么

let jsonUsers = [];
getUser() {
    const keys = Object.keys(this.jsonUsers);
    keys.forEach((k, i) => {
        const element = this.jsonUsers[k];
        console.log(element.code)
    })
}

或其他选项可能正在使用for...in

let jsonUsers = [];
getUser() {
    for (let k in this.jsonUsers) {
        const element = this.jsonUsers[k];
        console.log(element.code)
    }
}

请注意,this.jsonUsers是与jsonUsers不同的变量,请记住