这是我的函数,它应该验证名称,以便没有重复:
function validateBucketName(){
var counter = 1;
var validated = false;
var suggestedName = "Bucket " + (vm.buckets.length + counter);
if(vm.buckets.length === 0) return suggestedName;
while(!validated){
var foundIndex = vm.buckets.findIndex(function (bucket) {
return bucket.name === suggestedName;
});
if(foundIndex === -1){
validated = true;
} else {
counter++;
suggestedName = "Bucket " + (vm.buckets.length + counter);
}
}
return suggestedName;
}
我遇到了相当常见的错误,我知道如何在for
循环中处理,但无法弄清楚如何使用while
循环。有人可以看一下吗?
聚苯乙烯。这可能是非常低效的方法,试图确保不存在重复的名称。如果您有建议如何让它更好随意发表评论。
答案 0 :(得分:1)
您不需要validate
变量,只需使用while(true)
,因为您将获得遗失的suggestedName
。
当此条件if (foundIndex === -1)
为真时,请返回suggestedName
。
通过以下修改查看此代码段:
function validateBucketName() {
var counter = 1;
var suggestedName = "Bucket " + (vm.buckets.length + counter);
if (vm.buckets.length === 0) return suggestedName;
var compare = function(bucket) {
return bucket.name === suggestedName;
};
while (true) {
if (vm.buckets.findIndex(compare) === -1) {
return suggestedName;
else
suggestedName = "Bucket " + (vm.buckets.length + (counter++));
}
return suggestedName;
}