简体   繁体   中英

Jshint - Variable is already defined and missing semicolon of a javascript object

I defined a reason variable as javascript object inside a function, and then, use this object to define properties as following:

$scope.upsertReason = function() {
    var reason = {},
        reason.reasons = [],
        reason.scholarships = [];
}

I don't know why I always got the following error:

412 |            reason.reasons = [],
                       ^ 'reason' is already defined.
412 |            reason.reasons = [],
                       ^ Missing semicolon.
412 |            reason.reasons = [],
                       ^ Expected an identifier and instead saw '.'.
412 |            reason.reasons = [],
                       ^ Expected an assignment or function call and instead saw an expression.
412 |            reason.reasons = [],
                        ^ Missing semicolon.
413 |            reason.scholarships = [];
                                        ^ Expected an assignment or function

I have verified that I didn't define the reason variable anywhere else in the code. Any help would be appreciated.

You cannot declare a property of an object with var statement, because var statement expects the variable names not to contain invalid characters. And . is definitely an invalid character for an identifier name. So, you cannot declare a new variable called reason.reasons or reason.scholarships .

You should declare reason like this

var reason = {
    reasons: [],
    scholarships = []
};

Like thefourtheye said, you can either do this:

var reason = {
    reasons: [],
    scholarships = []
};

Or if you want to do it all separately, you can do:

var reason = {};
reason.reasons = [];
reason.scholarships = [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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