[英]How do I add a new element to an array of objects?
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: 任意整数
x
每个数组元素list[x]
是以下形式的对象:
{
name: "insert-name",
value: "insert-value"
}
I was told that for adding an element to an array, I must use the push()
function. 有人告诉我,要将元素添加到数组中,必须使用
push()
函数。 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. cc.list
是此模块.js
文件中数组的名称。 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?
以及如何使新的数组对象元素附加到此数组?
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
它正在使用名为
name
的变量,但是不存在这样的变量,因此ReferenceError: name is not defined
错误ReferenceError: name is not defined
You have made the same error with value
, there is no variable defined with that name. 您使用
value
犯了同样的错误,没有使用该名称定义变量。
You do however have variables named nname
and nvalue
, so perhaps this is what you were intending to write: 但是,您确实具有名为
nname
和nvalue
变量,因此也许这是您打算编写的:
return "Command successfully created! Typing `Z!" + nname +"` will output `" + nvalue +"` now!" ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.