为什么输出是未定义的?



所以,我在JS上制作玩具编程语言我遇到了一个麻烦…也就是标签。根据我的想法,标签之后的所有内容都被输入到对象中,然后在必要时运行代码:

var OBJcode = {}
labels = {}
code = `zhopa: i am string
i am string
i am string
i am string`
CodeLine = code.split("n")
for (var i = 0; i < CodeLine.length; i++) {
runCode = CodeLine[i].split(" ")
OBJcode[i] = runCode
label = runCode[0]
instruction = CodeLine[1]
src = runCode[2]
dst = runCode[3]
if (`${dst}` == "undefined") {
dst = src
src = instruction
instruction = label
}
if (label.endsWith(":")) labels[label.slice(0, -1)] += CodeLine[i + 1].split(" ").join(" ")
}
console.log(code)
console.log(OBJcode)
console.log(labels)

输出:

zhopa: i am string
i am string
i am string
i am string {
'0': ['zhopa:', 'i', 'am', 'string'],
'1': ['i', 'am', 'string'],
'2': ['i', 'am', 'string'],
'3': ['i', 'am', 'string']
} {
zhopa: 'undefinedi am string'
}

和如何添加下一行的标签[label]?

最有可能的问题是在21:56

你第一次这么做

labels[label.slice(0, -1)] += CodeLine[i + 1].split(" ").join(" ")

labels对象为空,因此labels[label.slice(0, -1)]未定义。当您连接到此时,它将未定义的值转换为字符串"undefined",然后将CodeLine[i + 1].split(" ").join(" ")附加到此。所以你在结果的开头得到undefined

您需要在连接之前检查对象属性是否存在。

var OBJcode = {}
labels = {}
code = `zhopa: i am string
i am string
i am string
i am string`
CodeLine = code.split("n")
for (var i = 0; i < CodeLine.length; i++) {
runCode = CodeLine[i].split(" ")
OBJcode[i] = runCode
label = runCode[0]
instruction = CodeLine[1]
src = runCode[2]
dst = runCode[3]
if (`${dst}` == "undefined") {
dst = src
src = instruction
instruction = label
}
if (label.endsWith(":")) {
let key = label.slice(0, -1);
let value = CodeLine[i + 1].split(" ").join(" ");
if (labels[key]) {
labels[key] += value;
} else {
labels[key] = value;
}
}
}
console.log(code)
console.log(OBJcode)
console.log(labels)

最新更新