是否有更简单或更短的方法来编写此重复代码?

时间:2015-06-02 21:23:40

标签: javascript

我想知道是否有更短/更简单的方法来编写重复代码。如果在提示框中输入的名称没有任何内容,则会发送错误消息并重新输入。

就这样,我不必解释很多,继承人的代码:

officeWebControls.directive('officeButton', ['$q', 'stylesheetInjectorService', function($q, stylesheetInjectorService) {
    return {
        restrict: 'E',
        replace: false,
        scope: {
            isDefault: '@',
            isDisabled: '@',
            api: '=',
            label: '@'
        },
        template: OFFICE_BUTTON_TEMPLATE,

        /**
         * @description
         * Provides the controller for the 'officeButton' directive. In this controller all the required methods
         * are being stored.
         */
        controller: ['$scope', function($scope) {
}],

        /**
         * @kind                    Directive caller
         *
         * @param scope             The scope which is passed to the directive.
         * @param element           The element on which this directive is being applied.
         * @param attributes        The attributes that are applied on the element on which this directive is
         *                          applied.
         * @param controller        The controller for this directive.
         */
        link: function(scope, element, attributes, controller) {
        }
    };
}]);

3 个答案:

答案 0 :(得分:9)

像这样:



var Name;

while(!(Name=prompt('What is your name?', 'Name'))) {
  alert('You must enter a name.');
}




工作原理

while循环重复,直到满足条件。在这种情况下,条件是:

!(Name=prompt('What is your name?', 'Name'))

表达式的这一部分将prompt值分配给Name(正如您已经知道的那样):

Name=prompt('What is your name?', 'Name')

在JavaScript中,对变量的赋值也返回值。 (这就是为什么我们可以将a = b = c = 16等分配链接起来。)

所以如果你输入" Johnathan"作为名称,这个表达式成为" Johnathan":

(Name=prompt('What is your name?', 'Name'))

如果您不输入任何内容作为名称,则表达式将变为空字符串。

表达式之前的逻辑NOT运算符(!)返回与"真实性相反的布尔值"的表达。字符串值为 truthy ,但空字符串为 falsy

将NOT运算符应用于表达式:

!(Name=prompt('What is your name?', 'Name'))

...循环将继续,直到Name变量具有值。

最后的想法:按照惯例,变量应该以小写字母开头。我在这里没有这样做,因为namewindow的属性,更改窗口的名称可能会导致问题。理想情况下,您的提示符将在函数内,因此您不会有任何全局变量。如果是这种情况,您可以像其他人建议的那样使用变量name

答案 1 :(得分:2)

虽然我喜欢在while循环中完成所有操作,但我自己也会这样做。它也值得理解它和do..while循环之间的区别,它可以帮助初学者按顺序阅读事物并理解每一步。

var name;
do {
  name = prompt('What is your name?', 'Name');
  if (name == '') {
    alert('You must enter a name.');
  }
} while (name == ''); // jump back to first line of *do* body if true.

答案 2 :(得分:0)

tee

只需在函数内部调用自己,仅在满足条件时退出。

相关问题