研究调查问卷:请告诉我们您使用 Blockly 的体验
开始调查问卷
变量字段
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
变量字段将字符串存储为值,并将字符串存储为文本。值是变量的 ID,而文本是变量的名称。
变量字段

打开编辑器后的变量字段

折叠块上的变量字段

创建
未输入
JSON
{
"type": "example_variable_untyped",
"message0": "variable: %1",
"args0": [
{
"type": "field_variable",
"name": "FIELDNAME",
"variable": "x"
}
]
}
JavaScript
Blockly.Blocks['example_variable_untyped'] = {
init: function() {
this.appendDummyInput()
.appendField('variable:')
.appendField(new Blockly.FieldVariable('x'), 'FIELDNAME');
}
};
类型化
JSON
{
"type": "example_variable_typed",
"message0": "variable: %1",
"args0": [
{
"type": "field_variable",
"name": "FIELDNAME",
"variable": "x",
"variableTypes": ["Number", "String"],
"defaultType": "Number"
}
]
}
JavaScript
Blockly.Blocks['example_variable_typed'] = {
init: function() {
this.appendDummyInput()
.appendField('variable:')
.appendField(new Blockly.FieldVariable(
'X',
null,
['Number', 'String'],
'Number'
), 'FIELDNAME');
}
};
变量构造函数接受可选的变量名称、可选的验证器、可选的变量类型数组和可选的默认类型。
- 变量名称应为字符串。这将是相应字段所保存的初始变量的名称。如果为 null 或 undefined,系统会生成一个唯一名称。
- 变量类型应为字符串数组。这会告知字段可以包含哪些类型的变量(即,要向下拉菜单中添加哪些类型的变量)。如果为 null 或未定义,则接受所有变量类型(并将其添加到下拉菜单中)。
- 默认类型应为字符串。这将在创建字段的初始变量模型时使用。如果定义了此属性,则应将其包含在变量类型数组中。如果此值为 null 或未定义,则此值默认为空字符串,这意味着初始变量将是灵活类型的。
→ 如需详细了解严格类型检查,请参阅类型检查。
序列化
JSON
变量字段的 JSON 如下所示:
{
"fields": {
"FIELDNAME": {
"id": "QJD^+@[RVIwbLSZoDb:V"
}
}
}
其中,FIELDNAME
是引用变量字段的字符串,相应的值是该字段所引用变量的 ID。
如果您在工具箱中使用此字段,还可以直接指定名称和(可选)类型,因为没有可供引用的变量。
{
"fields": {
"FIELDNAME": {
"name": "my_variable",
"type": "string"
}
}
}
XML
变量字段的 XML 如下所示:
<field name="VARIABLE" id="QJD^+@[RVIwbLSZoDb:V" variabletype="">name</field>
- 节点的
name
属性包含引用变量字段的字符串。
- 节点的
id
属性包含相应字段所引用的变量的 ID。
- 节点的
variabletype
属性包含变量的类型。
variabletype
遵循与构造函数的默认类型形参相同的规则。
- 节点的内部文本是变量的名称。内部文本值遵循与构造函数的变量名称参数相同的规则。
创建变量验证器
变量字段的值是字符串,因此任何验证器都必须接受字符串并返回字符串、null
或 undefined
。
以下是一个验证器的示例,该验证器仅接受一些预定义的变量作为选项。在加载工作区时,需要使用 Workspace.getVariableMap().createVariable
函数定义这些变量。
function(newValue) {
var validIds = ['Worf', 'Riker', 'Picard'];
if (validIds.indexOf(newValue) == -1) {
return null;
}
return newValue;
}

如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-05。
[null,null,["最后更新时间 (UTC):2025-08-05。"],[[["\u003cp\u003eVariable fields store a variable's ID as its value and the variable's name as its text, enabling blocks to interact with variables.\u003c/p\u003e\n"],["\u003cp\u003eYou can specify the variable's name, type, and validation rules during field creation to control its behavior.\u003c/p\u003e\n"],["\u003cp\u003eVariable fields can be serialized to JSON or XML for saving and loading block configurations.\u003c/p\u003e\n"],["\u003cp\u003eValidators can be used to restrict the variables a field can accept, ensuring data integrity.\u003c/p\u003e\n"],["\u003cp\u003eVariable fields can be pre-populated with specific variable names and types within the toolbox.\u003c/p\u003e\n"]]],[],null,["# Variable fields\n\nA variable field stores a string as its value, and a string as its text. The\nvalue is an ID of a variable, while the text is the name of a variable.\n\n#### Variable field\n\n#### Variable field with editor open\n\n#### Variable field on collapsed block\n\nCreation\n--------\n\n### Untyped\n\n### JSON\n\n {\n \"type\": \"example_variable_untyped\",\n \"message0\": \"variable: %1\",\n \"args0\": [\n {\n \"type\": \"field_variable\",\n \"name\": \"FIELDNAME\",\n \"variable\": \"x\"\n }\n ]\n }\n\n### JavaScript\n\n Blockly.Blocks['example_variable_untyped'] = {\n init: function() {\n this.appendDummyInput()\n .appendField('variable:')\n .appendField(new Blockly.FieldVariable('x'), 'FIELDNAME');\n }\n };\n\n### Typed\n\n### JSON\n\n {\n \"type\": \"example_variable_typed\",\n \"message0\": \"variable: %1\",\n \"args0\": [\n {\n \"type\": \"field_variable\",\n \"name\": \"FIELDNAME\",\n \"variable\": \"x\",\n \"variableTypes\": [\"Number\", \"String\"],\n \"defaultType\": \"Number\"\n }\n ]\n }\n\n### JavaScript\n\n Blockly.Blocks['example_variable_typed'] = {\n init: function() {\n this.appendDummyInput()\n .appendField('variable:')\n .appendField(new Blockly.FieldVariable(\n 'X',\n null,\n ['Number', 'String'],\n 'Number'\n ), 'FIELDNAME');\n }\n };\n\nThe variable constructor takes in an optional variable name, an optional\n[validator](#creating_a_variable_validator), an optional array of variable\ntypes, and an optional default type.\n\n- The **variable name** should be a string. This will be the name of the initial variable the field holds. If it is null or undefined a unique name will be generated.\n- The **variable types** should be an array of strings. This tells the field what types of variables the field can hold (i.e. what types of variables to add to the dropdown). If it is null or undefined, all variable types will be accepted (and added to the dropdown).\n- The **default type** should be a string. This will be used when creating the field's initial variable model. If this is defined, its should be included in the variable types array. If it is null or undefined this value defaults to an empty string, meaning the initial variable will be flexibly typed.\n\n→ For more information on strict typing, see\n[Type Checks](/blockly/guides/create-custom-blocks/type-checks).\n\nSerialization\n-------------\n\n### JSON\n\nThe JSON for a variable field looks like so: \n\n {\n \"fields\": {\n \"FIELDNAME\": {\n \"id\": \"QJD^+@[RVIwbLSZoDb:V\"\n }\n }\n }\n\nWhere `FIELDNAME` is a string referencing a variable field, and\nthe value is the ID of the variable the field references.\n\nIf you are using this field in the toolbox, you can also specify the name\nand (optional) type directly, since there will be no variable available to\nreference. \n\n {\n \"fields\": {\n \"FIELDNAME\": {\n \"name\": \"my_variable\",\n \"type\": \"string\"\n }\n }\n }\n\n### XML\n\nThe XML for a variable field looks like so: \n\n \u003cfield name=\"VARIABLE\" id=\"QJD^+@[RVIwbLSZoDb:V\" variabletype=\"\"\u003ename\u003c/field\u003e\n\n- The node's `name` attribute contains a string referencing a variable field.\n- The node's `id` attribute contains the ID of the variable the field references.\n- The node's `variabletype` attribute contains the type of the variable. The `variabletype` follows the same rules as the constructor's default type parameter.\n- The node's inner text is the name of the variable. The inner text value follows the same rules as the constructor's variable name parameter.\n\nCreating a variable validator\n-----------------------------\n\n| **Note:** For information on validators in general see [Validators](/blockly/guides/create-custom-blocks/fields/validators).\n\nA variable field's value is a string, so any validators must accept a string and\nreturn a string, `null`, or `undefined`.\n\nHere's an example of a validator that only accepts some predefined variables as\noptions. These variables would need to be defined with the\n[`Workspace.getVariableMap().createVariable`](/blockly/reference/js/blockly.ivariablemap_interface.createvariable_1_methodsignature)\nfunction when the workspace is loaded. \n\n function(newValue) {\n var validIds = ['Worf', 'Riker', 'Picard'];\n if (validIds.indexOf(newValue) == -1) {\n return null;\n }\n return newValue;\n }"]]