在 JavaScript 中终止外部映射函数
Terminate outer map function in JavaScript
我想在 if 条件通过时终止 map 函数
dataset.Categories.map(function (item) {
if(Object.keys(item)[0] == current_category){
return false;
}
else
category_position++;
});
这里的数据集是一个对象。即使条件通过,map 函数也会运行整个长度。
您实际问题之前的内容:
- 由于您不创建新数组,您可能希望使用
forEach()
。
- 我不记得在这些迭代器函数中看到过任何保证元素处理顺序的内容。
有人说要修复你的代码,我会引入一个变量来短路(因为 afaik 那些迭代器函数不能被取消):
var done = false,
category_position = 0;
dataset.Categories.map(function (item) {
if( done ) {
return;
}
if(Object.keys(item)[0] == current_category){
done = true
} else {
category_position += 1;
}
});
除此之外,我认为仅 for
循环最适合您:
var category_position;
for( category_position=0; category_position<dataset.Categories.length; category_position++ ) {
if(Object.keys(dataset.Categories[ category_position ])[0] == current_category){
break;
}
}
看来你真的很想用 Array.prototype.some
dataset.Categories.some(function (item) {
if (Object.keys(item)[0] == current_category) {
return true; // this will end the `some`
}
++category_position;
});
另外,你的测试最好写成
if (item.hasOwnProperty(current_category)) { // etc
因为这避免了涉及 Object
上的多个键顺序的问题
我想在 if 条件通过时终止 map 函数
dataset.Categories.map(function (item) {
if(Object.keys(item)[0] == current_category){
return false;
}
else
category_position++;
});
这里的数据集是一个对象。即使条件通过,map 函数也会运行整个长度。
您实际问题之前的内容:
- 由于您不创建新数组,您可能希望使用
forEach()
。 - 我不记得在这些迭代器函数中看到过任何保证元素处理顺序的内容。
有人说要修复你的代码,我会引入一个变量来短路(因为 afaik 那些迭代器函数不能被取消):
var done = false,
category_position = 0;
dataset.Categories.map(function (item) {
if( done ) {
return;
}
if(Object.keys(item)[0] == current_category){
done = true
} else {
category_position += 1;
}
});
除此之外,我认为仅 for
循环最适合您:
var category_position;
for( category_position=0; category_position<dataset.Categories.length; category_position++ ) {
if(Object.keys(dataset.Categories[ category_position ])[0] == current_category){
break;
}
}
看来你真的很想用 Array.prototype.some
dataset.Categories.some(function (item) {
if (Object.keys(item)[0] == current_category) {
return true; // this will end the `some`
}
++category_position;
});
另外,你的测试最好写成
if (item.hasOwnProperty(current_category)) { // etc
因为这避免了涉及 Object
上的多个键顺序的问题