如何在 javascript 中将字符串转换为布尔值?
How to convert string to Boolean in javascript?
我有一个 public 属性 从我的代码隐藏 class 返回到 aspx
页面:
window.MyWIndow.IsFull = '<%=this.IsFull%>';
在代码隐藏中它是这样定义的:
public bool IsFull
{
get;
set;
}
现在,当我在 javascript 文件中使用它时,我有以下代码:
var isShow = myself.IsFull;
这样 isShow
要么是 'True'
要么是 'False'
我需要在页面级别转换它,所以 isShow
是 boolean
而不是 string
。
所以我可以写 if else
逻辑
我该怎么做?
您可以使用JSON.parse('true');
JSON.parse(isShow.toLowerCase());
试试下面的例子。
var result = ['True', 'False']
var isShow = result[Math.round(Math.random())];
console.log(JSON.parse(isShow.toLowerCase()));
如果您知道它总是 return 字符串 True 和 False,您可以只使用;
window.MyWindow.IsFull = '<%=this.IsFull%>' === "True";
替代方法是
window.MyWIndow.IsFull = <%=this.IsFull.ToString().ToLower()%>;
注意,没有引号
答错就是错...
A couple of options. You can use the built in Boolean
object
wrapper
like this:
var string = myself.IsFull
var isShow = new Boolean(string.toLowercase);
or use the logical
NOT
operator twice like this:
var string = myself.IsFull
var isShow = !(!string.toLowercase);
edit: but why???? [![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/359zg.png
我有一个 public 属性 从我的代码隐藏 class 返回到 aspx
页面:
window.MyWIndow.IsFull = '<%=this.IsFull%>';
在代码隐藏中它是这样定义的:
public bool IsFull
{
get;
set;
}
现在,当我在 javascript 文件中使用它时,我有以下代码:
var isShow = myself.IsFull;
这样 isShow
要么是 'True'
要么是 'False'
我需要在页面级别转换它,所以 isShow
是 boolean
而不是 string
。
所以我可以写 if else
逻辑
我该怎么做?
您可以使用JSON.parse('true');
JSON.parse(isShow.toLowerCase());
试试下面的例子。
var result = ['True', 'False']
var isShow = result[Math.round(Math.random())];
console.log(JSON.parse(isShow.toLowerCase()));
如果您知道它总是 return 字符串 True 和 False,您可以只使用;
window.MyWindow.IsFull = '<%=this.IsFull%>' === "True";
替代方法是
window.MyWIndow.IsFull = <%=this.IsFull.ToString().ToLower()%>;
注意,没有引号
答错就是错...
A couple of options. You can use the built in
Boolean
object wrapper like this:var string = myself.IsFull var isShow = new Boolean(string.toLowercase);
or use the logical NOT operator twice like this:
var string = myself.IsFull var isShow = !(!string.toLowercase);
edit: but why???? [![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/359zg.png