研究调查问卷:请告诉我们您使用 Blockly 的体验
开始调查问卷
数字字段
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
数字字段会将数字存储为 value
,并将字符串存储为 text
。其 value
始终是有效数字,具体取决于在创建时为该字段指定的限制条件;其文本可以是输入到其编辑器中的任何字符串。
数字字段

打开编辑器的数字字段

收起的版块上的数字字段

创建
JSON
{
"type": "example_number",
"message0": "number: %1",
"args0": [
{
"type": "field_number",
"name": "FIELDNAME",
"value": 100,
"min": 0,
"max": 100,
"precision": 10
}
]
}
JavaScript
Blockly.Blocks['example_number'] = {
init: function() {
this.appendDummyInput()
.appendField("number:")
.appendField(new Blockly.FieldNumber(100, 0, 100, 10), 'FIELDNAME');
}
};
数字构造函数接受以下内容:
value
应转换为数字。如果没有,则使用 0。
序列化
JSON
数字字段的 JSON 如下所示:
{
"fields": {
"FIELDNAME": 0
}
}
其中 FIELDNAME
是引用数字字段的字符串,值是应用于该字段的值。该值遵循与构造函数值相同的规则。
XML
数字字段的 XML 如下所示:
<field name="FIELDNAME">0</field>
field
节点的 name
属性包含引用数字字段的字符串,并且节点的内部 text
是应用于该字段的 value
。内部文本值遵循与构造函数值相同的规则。
限制条件
您可以在字段定义中设置约束条件,也可以使用 setConstraints 函数设置约束条件。
最小值
min
值用于设置字段允许包含的最小/最负值。
最大值
max
值用于设置字段允许包含的最大/最正值。
舍入
precision
会将值舍入到最接近的精度倍数。这可用于使字段仅接受 .01、10、42 等的倍数。
常见约束条件
正数
如需强制字段仅接受正数,请将 min
值设置为 1。
整数
如需强制字段仅接受整数,请将 precision
设置为 1。
创建数字验证器
数字字段的值是数字,因此任何验证器都必须接受 number
并返回 number
、null
或 undefined
。
以下示例展示了一个验证器,它会根据值是奇数还是偶数将值更改为 0 或 1。
function(newValue) {
return newValue % 2;
}

如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-25。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-07-25。"],[[["A number field stores numeric data using `value` for the number itself and `text` for its string representation, adhering to specified constraints."],["Number fields can be created through JSON or JavaScript, allowing customization of initial values, minimums, maximums, and precision."],["Serialization of number fields is supported in JSON and XML, facilitating data storage and retrieval."],["Constraints like minimum/maximum values, rounding precision, and custom validators can be applied to control the allowed numeric input."],["Number field validators, accepting and returning numeric values, enable enforcing specific data formats or ranges, such as limiting input to even or odd numbers."]]],["A number field stores a numerical `value` and a string `text`. The `value` is a valid number, while the `text` is any string. Fields are created via JSON or JavaScript, defining `value`, optional `min`, `max`, and `precision`. Constraints set the allowed range and rounding. Serialization uses JSON or XML to represent the field's `value`. Validators can be defined, accepting a number and returning a number, `null`, or `undefined`, allowing for custom logic like enforcing even or odd numbers.\n"]]