因此,我在 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'
}
以及如何將下一行添加到標簽[標簽]?
問題很可能出現在 21:56
uj5u.com熱心網友回復:
你第一次這樣做
labels[label.slice(0, -1)] = CodeLine[i 1].split(" ").join(" ")
labels物件是空的,所以labels[label.slice(0, -1)]是未定義的。當您連接到 this 時,它會將 undefined 值轉換為 string "undefined",然后CodeLine[i 1].split(" ").join(" ")附加到 this 上。所以你得到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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488762.html
標籤:javascript 节点.js 数组 目的
上一篇:具有大型陣列索引的映射函式中的時間復雜度是否會受到影響
下一篇:如何在同一物件的回圈中合并陣列?
