JSLint - 声明变量的问题 [英] JSLint - problems declaring variables

查看:69
本文介绍了JSLint - 声明变量的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码传递JSLint:

The following code passes JSLint:

var sGreeting = 'hello world';

switch (sGreeting)
{
case 'Hello world!':
    var a = 'some a value';
    break;
case 'Kamusta mundo!':
    var b = 'some b value';
    break;
case 'Salut le Monde!':
    var c = 'some c value';
    break;
default:
    break;
}

但是,一旦我将该代码放入函数中,JSLint就会抱怨我应该将...与前面的'var'语句结合使用。如果我遵循JSLint,我将定义可能永远不需要使用的变量。 我应该如何处理这个问题?以下是JSLint错误后面的代码:

However, once I put that code in a function, JSLint complains that I should Combine ... with the previous 'var' statement. If I follow JSLint, I would be defining variables that may never need to be used. How should I deal with this problem? Here's the code followed by JSLint's errors:

function foo()
{
    'use strict';
    var sGreeting = 'hello world';

    switch (sGreeting)
    {
    case 'Hello world!':
        var a = 'some a value';
        break;
    case 'Kamusta mundo!':
        var b = 'some b value';
        break;
    case 'Salut le Monde!':
        var c = 'some c value';
        break;
    default:
        break;
    }
}


Error:
Problem at line 9 character 7: Combine this with the previous 'var' statement.
var a = 'some a value';

Problem at line 12 character 7: Combine this with the previous 'var' statement.
var b = 'some b value';

Problem at line 15 character 7: Combine this with the previous 'var' statement.
var c = 'some c value';


推荐答案

javascript中唯一的范围是功能范围(括号做)不提供范围),所以switch语句中的那些vars正在悬挂到顶部功能。

The only scope in javascript is functional scope (braces do not provide scope), so those vars in the switch statement are being hoisted to the top of the function.

jslint建议的是:

What jslint is suggesting is this:

function foo() {
    'use strict';
    var a, b, c, sGreeting;

    sGreeting = 'hello world';

    switch (sGreeting) {
    case 'Hello world!':
        a = 'some a value';
        break;
    case 'Kamusta mundo!':
        b = 'some b value';
        break;
    case 'Salut le Monde!':
        c = 'some c value';
        break;
    default:
        break;
    }
}

这篇关于JSLint - 声明变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆