我需要幫助將以下 JS 函式轉換為 vb.net:
function testjs(s) {
var dict = {};
var data = (s "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i ) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase currChar;
code ;
oldPhrase = phrase;
}
return out.join("");
}
我的代碼目前的樣子:
Private Function questionmarkop(ByVal ph As String, ByVal dictatcurr As String, ByVal ophoc As String) As String
Return If(ph = dictatcurr, dictatcurr, ophoc)
End Function
Private Function testvb(ByVal s As String) As String
Dim dict As New Dictionary(Of Integer, String)
Dim data As Char() = s.ToCharArray
Dim currchar As Char = data(0)
Dim oldphrase As String = currchar
Dim out As String() = {currchar}
Dim code As Integer = 256
Dim phrase As String = ""
Dim ret As String = ""
For i As Integer = 1 To data.Length - 1
Dim currcode As Integer = Convert.ToInt16(data(i))
If currcode < 256 Then
phrase = data(i)
Else
phrase = questionmarkop(phrase, dict(currcode), (oldphrase currchar))
End If
ReDim Preserve out(out.Length)
out(out.Length - 1) = phrase
currchar = phrase(0)
dict.Item(code) = oldphrase currchar
code = 1
oldphrase = phrase
Next
For Each str As String In out
ret = ret str
Next
Return ret
End Function
輸入以下字串 s 時:this?averyshorttest?ringtogi?anexamplef??acko?rflow
該函式應回傳:thisisaveryshortteststringtogiveanexampleforstackoverflow
js 函式正是這樣做的,我的 vb 函式沒有。第一次(或基本上每次)if 陳述句不正確,下一個字符將是錯誤的。所以我認為這條線有問題phrase = questionmarkop(phrase, dict(currcode), (oldphrase currchar))。使用我提供的測驗字串,一切正常,直到this,之后我有了第一個假字符。有人可以幫我弄清楚我在這里做錯了什么嗎?
uj5u.com熱心網友回復:
根據評論中的討論,似乎該問題正在為該行生成 VB 翻譯:
phrase = dict[currCode] ? dict[currCode] : (oldPhrase currChar);
我只熟悉 Javascript,但我相信這里的關鍵是,dict[currCode]如果字典中還沒有帶有 key 的條目,它將回傳一種 null 或缺失值currCode。.NET 字典具有可以讓您獲得相同效果的功能,但具體實作方式略有不同。
等效于這個三元和賦值的直接 VB 是(我相信):
phrase = If(dict.ContainsKey(currCode), dict(currCode), oldPhrase & currChar)
您可以使用以下方法消除對字典的鍵查找Dictionary.TryGetValue:
If Not dict.TryGetValue(currCode, phrase) Then
phrase = oldPhrase & currChar
End If
我懷疑代碼是否對性能敏感到足以關心差異,所以我建議使用您覺得更容易閱讀的替代方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/506286.html
標籤:javascript VB.net
