简体   繁体   English

如何通过闭幕警告从while循环中访问如何修复可变变量

[英]how to fix mutable variable is accessible from closure warning with a while loop

Here's my function that is supposed to validate a name so that there is no duplicates: 这是我的功能,应该用来验证名称,以便没有重复项:

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;
    }

I am getting the pretty common error, that I am aware of how to deal with in for loops, but can't figure out how to do that with the while loop. 我遇到了一个非常常见的错误,我知道如何处理in for循环,但是无法弄清楚使用while循环该怎么做。 Can someone have a look at this? 有人可以看看吗?

Ps. PS。 This is probably very inefficient way of trying to make sure no duplicate names exist. 这可能是确保没有重复名称的非常​​无效的方法。 If you have a suggestion for how to make that better feel free to comment. 如果您有关于如何更好地提出建议,请随时发表评论。

This is a better approach 这是一个更好的方法

  • You don't need the validate variable, just use while(true) because you're going to get the missing suggestedName . 您不需要validate变量,只需使用while(true)因为您将获得缺少的suggestedName

  • When this condition if (foundIndex === -1) is true return the suggestedName . 当这种情况if (foundIndex === -1)是真正的回报suggestedName

Look this code snippet with those modifications: 请看一下这些修改后的代码片段:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM