简体   繁体   中英

populate a array from a JavaScript response

I am trying to take a response from my database that is in a JSON array. In this case, the array has 4 elements. I get how many elements in the response array "arrayLength" Init the new array with the same number of elements then I try and populate the array from the database response. this code does not work not sure why or what i am doing wrong.

console.log('$response',$response.CardList[0].CNUMBER);  

var count = 0;
var i = 0
var arrayLength = $response.CardList.length;
console.log("my lenghth=",arrayLength );


var cardNumberArray =new Array[arrayLength];
console.log("my lenghth2=",cardNumberArray );


for ( i = 0; i < arrayLength ; i++ ){
  cardNumberArray[i] = JSON.stringify($response.CardList[i].CNUMBER)

}

You're declaring cardNumberArray as an Array , but then selecting an index, which is done using [] square brackets. This index doesn't exist, so it's returning undefined . You're then selecting and index from undefined , which is what's giving you the error, which is Cannot read property 'i' of undefined .

How you would fix it, is to replace the square brackets with normal brackets, like this.

 let $response={CardList:[{CNUMBER:0},{CNUMBER:1},{CNUMBER:2},{CNUMBER:3}]} var count = 0; var i = 0 var arrayLength = $response.CardList.length; var cardNumberArray =new Array(arrayLength); for ( i = 0; i < arrayLength; i++ ){ cardNumberArray[i] = JSON.stringify($response.CardList[i].CNUMBER) } console.log(cardNumberArray)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM