我有以下代码:
var select_ids = [];
// syntax.filter.select_list is ["elem1", "elem2"]
for (var o = 0; o < syntax.filter.select_list.length; o += 1) {
element = syntax.filter.select_list[o];
if (priv.getPositionInArray(element,select_ids) === null ) {
// this line hangs up the browser
select_ids.unshift(element);
}
}
我不明白为什么在循环两次迭代时将 push() 或 unshift() 放入一个空数组会使浏览器挂起 3-4 秒。
如果我离开这条线:
select_ids.unshift(element);
脚本立即运行,所以
问题:
为什么 push/unshift 到一个空数组会产生这样的延迟?仅供参考,这是在另一个循环中进行 3 次迭代。对于每个父循环,我将 select_ids 重置为要填充的空对象。
谢谢!
编辑:
我正在做 if 子句以确保我不会将双精度数添加到数组中。
编辑:(完整代码)
priv.findBestIndexForQuery = function (indices, syntax) {
var i, j, k, l, m, n, p, o, element,
search_ids = [], select_ids = [], use_index = [],
index, query_param, search_param,
// need to parse into object
current_query = jIO.ComplexQueries.parse(syntax.query);
// loop indices
for (i = 0; i < priv.indices.length; i += 1) {
index = {};
index.reference = priv.indices[i];
index.reference_size = index.reference.fields.length;
// rebuild for iteration
if (current_query.query_list === undefined) {
search_ids.push(current_query.id);
} else {
for (j = 0; j < current_query.query_list.length; j += 1) {
if (priv.getPositionInArray(current_query.query_list[j].id,
search_ids) === null ) {
search_ids.push(current_query.query_list[j].id);
}
}
}
for (o = 0; o < syntax.filter.select_list.length; o += 1) {
element = syntax.filter.select_list[o];
if (priv.getPositionInArray(element,select_ids) === null ) {
// line causing problems
select_ids.unshift(element);
}
}
// there is a lot more, but I'm hanging on the line above
}
编辑(getPostionInArray)
priv.getPositionInArray = function (element, array) {
var i;
for (i = 0; i < array.length; i += 1) {
if (array[i] === element) {
return i;
}
}
return null;
};