I think this function will create "holes" in the array because of the condition in your for loop. Instead of using the same length for reviews_
and reviews
, you could create an empty reviews_
array, and push elements to it instead (see example, getShortList
, below)
Having a holey list will look something like this
[review1, , , , review5, review6, , review8];
Instead of having unknown elements, you either have to fill the blanks with a null
-able elements, e.g. an empty review
[review1, emptyReview, emptyReview, emptyReview, review5, review6, emptyReview, review8];
Or just make sure the list only contains elements without any "holes" in the array (a "packed" array)
[review1, review5, review6, review8];
Consider the following example
// Will panic at runtime due to holes in the list
getListWithHoles(): string[] {
const arr = new Array<string>(5);
for (let i = 0; i < arr.length; ++i) {
if (i > 2) {
arr[i] = "";
}
}
return arr; // will return [,,,"",""];
}
// Here's how we can fix it. Return a "packed" array
getShortList(): string[] {
const arr: string[] = [];
for (let i = 0; i < 5; ++i) {
if (i > 2) {
arr.push("");
}
}
return arr; // will return ["",""];
}