0

I want to add a new element to my array of objects. Each array element list[x] for an arbitrary integer x is an object of the form:

{
    name: "insert-name",
    value: "insert-value"
}

I was told that for adding an element to an array, I must use the push() function. So that is what I did:

exports.handle = function(input) {
for(var i=0; i<cc.list.length; i++) {
    if(input == cc.list[i].name) {
        return cc.list[i].value;
    }
}

if(input.startsWith("create-cc")) {
    var namevalue = input.slice(10, input.length);
    var spaceloc = namevalue.indexOf(" ");
    var nname = namevalue.slice(0, spaceloc);
    var nvalue = namevalue.slice(spaceloc+1, namevalue.length);

    cc.list.push({
        name: nname,
        value: nvalue
    });

    return "Command successfully created! Typing `Z!" + name +"` will output `" + value +"` now!" ;
}

return "Error.";

};

cc.list is the name of the array in this module .js file. I use the inputs from a user to be filled as the name and value for the new array element that I want to add to the list. However I got an error on the console, which told me:

ReferenceError: name is not defined

This totally makes sense, since I did not declare such a parameter. But doesn't that parameter already exist as a part of the "template" object that forms the array element? Why does this method not work? And how do I make a new array object element to be appended to this array?

4
  • name is not defined nname => name Commented May 9, 2018 at 16:21
  • @WalterChapilliquen-wZVanG Can you elaborate please? I dont really understand what you mean. Commented May 9, 2018 at 16:21
  • 1
    The error specifically is referring to the use of the variable name in your return statement, which does not exist in any scope. Commented May 9, 2018 at 16:22
  • 1
    At what line do you get the error? I would assume that it comes from the return-statement and not the object creating. When returning you are referencing name and value, instead of the object parameters. Commented May 9, 2018 at 16:22

1 Answer 1

2

The issue is with this line:

return "Command successfully created! Typing `Z!" + name +"` will output `" + value +"` now!" ;

It is making use of a variable named name, however no such variable exists, hence the error ReferenceError: name is not defined

You have made the same error with value, there is no variable defined with that name.

You do however have variables named nname and nvalue, so perhaps this is what you were intending to write:

return "Command successfully created! Typing `Z!" + nname +"` will output `" + nvalue +"` now!" ;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.