Reputation: 1342
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?
Upvotes: 0
Views: 70
Reputation: 2759
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!" ;
Upvotes: 2