研究调查问卷:请告诉我们您使用 Blockly 的体验
开始调查问卷
数字字段
数字字段将数字存储为其 value
,将字符串存储为其 text
。现在是 value
始终是一个有效的数字,根据给定的约束条件定义
在创建时指定的字段其文本可以是在编辑器中输入的任何字符串。
数字字段

编辑器已打开的编号字段

收起的块上的数字字段

恣意创作
{
"type": "example_number",
"message0": "number: %1",
"args0": [
{
"type": "field_number",
"name": "FIELDNAME",
"value": 100,
"min": 0,
"max": 100,
"precision": 10
}
]
}
Blockly.Blocks['example_number'] = {
init: function() {
this.appendDummyInput()
.appendField("number:")
.appendField(new Blockly.FieldNumber(100, 0, 100, 10), 'FIELDNAME');
}
};
数字构造函数采用以下参数:
value
应转换为数字。否则将使用 0。
序列化
数字字段的 JSON 如下所示:
{
"fields": {
"FIELDNAME": 0
}
}
其中 FIELDNAME
是引用数字字段的字符串,以及
值是应用于该字段的值。值
遵循与构造函数值相同的规则。
数字字段的 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):2024-09-09。
[null,null,["最后更新时间 (UTC):2024-09-09。"],[[["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"]]