Collada 文件格式包含大量数据,这些数据存储为以空格分隔的 float/int/boolean 值列表。这些列表可能巨大。我们大致使用以下代码在 JavaScript 中解析这些列表:
var floats = input.split(' ').map(parseFloat)
但这会产生大量垃圾,因为巨大的输入字符串被分割成数千个单独的小字符串。有办法避免这种情况吗?类似于 parseFloat() 函数,我可以指向现有字符串中的偏移量,从而避免生成垃圾。
最佳答案
如果在字符串前添加一个空格,则可以使用它来获取字符串中的第一个数字:
var start = 0 // Initial search offset.
var firstOccurence = input.indexOf(' ', start);
//Get the substring from the first occurrence of ' ' after start, to the next one, and parse it as a float.
parseFloat(input.substring(firstOccurence , input.indexOf(' ', firstOccurence+1)));
然后,您可以使用以下命令从字符串中获取之后的数字:
firstOccurence = t.indexOf(' ', firstOccurence+1);
parseFloat(t.substring(firstOccurence , t.indexOf(' ', firstOccurence+1)));
在循环中使用它,您可以搜索列表,并且可以从指定索引处开始搜索列表。但是,例如,您不能请求列表中的第七个 float 。唯一可靠的方法是使用 .split(' ')
,或在循环中使用上述代码。
要查找输入中的第 n 个 float ,您可以使用以下命令:
for(var i = 0, previousIndex = 0; i < n; i++){
previousIndex = input.indexOf(' ', previousIndex + 1);
}
var float = parseFloat(input.substring(previousIndex, input.indexOf(' ', previousIndex + 1)));
关于javascript - 在 JavaScript 中将字符串高效解析为 float 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13563988/