考虑下面的打字脚本:
const myArray: Array<string> = new Array();
myArray[5] = 'hello';
myArray[7] = 'world';
const len = myArray.length;
let totalLen = 0;
myArray.forEach( arr => totalLen++);
console.log('Total elements in the array: ' + len.toString(10));
console.log('Total defined elements in the array: ' + totalLen.toString(10));输出:
Total elements in the array: 8
Total defined elements in the array: 2我需要将数据插入到任意索引处的数组中,这会创建未定义的数组元素。然后,我需要检查数组中已定义元素的总数。.length包含未定义的元素,但.forEach只迭代已定义的元素。
似乎应该有更好的方法来做这件事,但我就是不知道正确的方法。
发布于 2020-07-15 22:19:34
您可以过滤数组,然后找到长度,如下所示:
myArray.filter(i => i !== undefined).length
https://stackoverflow.com/questions/62917024
复制相似问题