javascript - js中将字符串转成布尔值
表单中按钮获取的值是字符串string类型,但是提交给后台的数据需要布尔值。有以下三种方式进行转换:1、使用JSON.parse()将字符串‘true’、‘false’转换成布尔值<form><input type="radio" name="Status" value="true" οnclick="getValue(this.value)" /><input ty
·
表单中按钮获取的值是字符串string类型,但是提交给后台的数据需要布尔值。
有以下三种方式进行转换:
1、使用JSON.parse()将字符串‘true’、‘false’转换成布尔值
字符串‘true’、‘false’必须全部小写,否则会引起json字符串转换异常
<form>
<input type="radio" name="Status" value="true" οnclick="getValue(this.value)" />
<input type="radio" name="Status" value="false" οnclick="getValue(this.value)" />
</form>
function getValue(value){
console.log(JSON.parse(value))
}
2、使用Boolean()及parseInt(),将字符串‘0’、‘1’转换为布尔值
<form>
<input type="radio" name="Status" value="0" οnclick="getValue(this.value)" />
<input type="radio" name="Status" value="1" οnclick="getValue(this.value)" />
</form>
function getValue(value){
console.log(Boolean(parseInt(value)))
}
3、使用if语句对value值进行判断
<form>
<input type="radio" name="Status" value="任意" οnclick="getValue(this.value)" />
<input type="radio" name="Status" value="的值" οnclick="getValue(this.value)" />
</form>
function getValue(value){
let flag=true;
if(value=='任意'){
console.log(flag)
}else if(value=='的值'){
console.log(!flag)
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)