字符串连接 - Scratch扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
(function() {
'use strict'
class StrConnect {
getInfo() {
return {
id: "stringconnect",
name: "字符串连接",
color1: "#3271D0",
blocks: [
{
opcode: "strconnect",
blockType: Scratch.BlockType.REPORTER,
text: "将 [TEXT] 中的 %c 替换为 [LIST] 中的每一项",
arguments: {
TEXT: {
type: Scratch.ArgumentType.STRING,
default: ""
},
LIST: {
type: Scratch.ArgumentType.STRING,
menu: "get_list",
},
},
}
],
menus: {
get_list: {
acceptReporters: false,
items: "getLists",
},
}
};
}

getLists() {
const globalLists = Object.values(
Scratch.vm.runtime.getTargetForStage().variables
).filter((x) => x.type === "list");
const localLists = Scratch.vm.editingTarget
? Object.values(Scratch.vm.editingTarget.variables).filter(
(x) => x.type === "list"
)
: [];
const uniqueLists = [...new Set([...globalLists, ...localLists])];
if (uniqueLists.length === 0) {
return [
{
text: "select a list",
value: "select a list",
},
];
}
return uniqueLists.map((i) => ({
text: i.name,
value: i.id,
}));
}

lookupList(list, util) {
const byId = util.target.lookupVariableById(list);
if (byId && byId.type === "list") {
return byId;
}
const byName = util.target.lookupVariableByNameAndType(list, "list");
if (byName) {
return byName;
}
return null;
}

strconnect(args, util) {
try {
let listVariable = this.lookupList(args.LIST, util);
if (listVariable) {
const values = listVariable.value;
let res = args.TEXT;
for (let i = 0; i < values.length; i++) {
res = res.replace("%c", values[i]);
if (res.indexOf("%c") == -1) break;
}
return res;
}
} catch (e) {
// ignore
}
return "";
}
}
Scratch.extensions.register(new StrConnect());
})(Scratch);

示例:

参数 TEXT 参数 LIST(内容) 输出
将%c进行替换 将我进行替换
这里的TEXT只有%c个%c,而列表有%c项 3,%c,4,第四项 这里的TEXT只有3个%c,而列表有4项

字符串连接 - Scratch扩展
https://qiufengcute.github.io/Blog/posts/Scratch扩展/字符串连接/
作者
Qiufeng
发布于
2026年3月2日
许可协议