javascript 如何在knockout.js 中检查值是否为NULL 或未分配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26480021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How the check if a value is NULL or unassigned in knockout.js?
提问by pcbabu
Suppose in this example, firstName
is not set and lastName
is assigned a value. How to check if the value is assigned or not.
假设在此示例中,firstName
未设置并 lastName
分配了一个值。如何检查值是否已分配。
function AppViewModel() {
this.firstName = ko.observable();
this.lastName = ko.observable('Smith');
}
Which one is the best approach? Will these work?
哪一种是最好的方法?这些会起作用吗?
if(lastName == '')
//do something
or
或者
if(lastName)
//do something
or
或者
if(lastName == null)
//do something
Please help.
请帮忙。
采纳答案by joshmcode
I know the OP's question/example was in JavaScript, but I stumbled on this question because of the title:
我知道 OP 的问题/示例是在 JavaScript 中,但由于标题,我偶然发现了这个问题:
How to check if a value is NULL or unassigned in knockout.js?
如何检查knockout.js 中的值是否为NULL 或未分配?
This can ALSO be checked in the view, very simply: (example is from Knockout's example code here):
这也可以在视图中检查,非常简单:(示例来自此处的Knockout 示例代码):
<div data-bind="if: capital">
Capital: <b data-bind="text: capital.cityName"> </b>
</div>
In this example there is an object called capital and the if
statement checks for null by default. If Capital is not null, then the second line is executed, otherwise it skips it. This works really well for simple cases.
在此示例中,有一个名为 capital 的对象,该if
语句默认检查是否为 null。如果 Capital 不为空,则执行第二行,否则跳过它。这对于简单的情况非常有效。
回答by Suchit kumar
you can check like:
你可以像这样检查:
if(lastName != undefined && lastName().length > 0 ){
// do something else.
}
Edit: You have to invoke lastName
as a function because it is an observable to read its current value.
编辑:您必须lastName
作为函数调用,因为它是读取其当前值的可观察对象。