英文:
Check if js.Value exists
问题
在JavaScript代码中,我有以下内容:
function readAll() {
var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + ", Value: " + cursor.value);
cursor.continue();
} else {
alert("No more entries!");
}
};
}
在我的等效GO代码中,我写了以下内容:
var ReadAll js.Func
ReadAll = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
defer ReadAll.Release()
cursor := this.Get("result")
if cursor {
_ = cursor.Get("key")
value := cursor.Get("value")
Window.Call("alert", value)
cursor.Call("continue")
} else {
Window.Call("alert", "No more records")
}
return nil
})
db.ObjectStore.Call("openCursor").Set("onsuccess", ReadAll)
但是在编译时,我得到了以下错误:
non-bool cursor (type js.Value) used as if condition
我该如何检查相关的js.value
是否存在?
英文:
In the JavaScript code, I've:
function readAll() {
var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + ", Value: " + cursor.value);
cursor.continue();
} else {
alert("No more entries!");
}
};
}
In my equivalent GO code, I wrote:
var ReadAll js.Func
ReadAll = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
defer ReadAll.Release()
cursor := this.Get("result")
if cursor {
_ = cursor.Get("key")
value := cursor.Get("value")
Window.Call("alert", value)
cursor.Call("continue")
} else {
Window.Call("alert", "No more records")
}
return nil
})
db.ObjectStore.Call("openCursor").Set("onsuccess", ReadAll)
But while compiling, I got:
non-bool cursor (type js.Value) used as if condition
Ho can I check if the related js.value
exists or no?
答案1
得分: 1
javascript中的if(cursor)
是检查值是否为truthy。
你的代码this.Get
返回一个js.Value
。它不是布尔值,不能在Go的if
语句中使用。
syscall/js包中有一个Truthy()
函数,你可以使用它来模拟javascript的truthy检查。
https://pkg.go.dev/syscall/js#Value.Truthy
if cursor.Truthy() {
...
}
要检查一个值是否为falsey,你可以对结果取反:
if !cursor.Truthy() {
...
}
英文:
The javascript if(cursor)
is checking if the value is truthy.
Your code this.Get
result in a js.Value
. It's not boolean, and you can't use it in a Go if
clause.
The syscall/js package has Truthy()
that you can use to mimick javascript truthy check.
https://pkg.go.dev/syscall/js#Value.Truthy
if cursor.Truthy() {
...
}
And to check if a value is falsey, you negate the result:
if !cursor.Truthy() {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论