使用ifc.js的getAllItemsOfType()时遇类型转换错误求助
问题解决:Cannot convert "undefined" to unsigned int 错误处理
问题根源
- 循环边界错误:
logAllSlabs里的循环用了i <= slabsID.length,数组索引从0开始到length-1,当i等于数组长度时,slabsID[i]会返回undefined,将这个undefined传给getItemProperties时,会触发类型转换错误——该函数需要合法的无符号整数ID,不能是undefined。 - 硬编码模型ID隐患:代码里直接写死
modelID=0和getItemProperties(0, ...),如果后续加载多个模型,模型ID会递增,硬编码0会导致获取属性时匹配错误。
修正代码
调整logAllSlabs函数
async function logAllSlabs(modelID) { const slabsID = await ifcLoader.ifcManager.getAllItemsOfType(modelID, IFCSLAB); // 把<=改成<,避免数组越界 for(let i = 0; i < slabsID.length; i++) { const slabID = slabsID[i]; const slabProperties = await ifcLoader.ifcManager.getItemProperties(modelID, slabID); console.log(slabProperties); } }
修正加载回调的调用逻辑
// IFC loading const ifcLoader = new IFCLoader(); const input = document.getElementById('file-input') input.addEventListener('change', async () => { console.log('file selected') const file = input.files[0]; const url = URL.createObjectURL(file); const model = await ifcLoader.loadAsync(url); scene.add(model); ifcModels.push(model); // 传入加载模型自带的modelID,不用硬写0 logAllSlabs(model.modelID); });
额外提示
- 遍历数组时,记住索引范围是
0到length-1,用< length是标准写法,能避免绝大多数数组越界问题。 - IFCLoader加载完成的模型会自动生成
modelID属性,直接使用这个值能保证和模型一一对应,避免硬编码带来的潜在bug。
内容的提问来源于stack exchange,提问作者ChenChihYuan
相关产品推荐
相关产品推荐

