Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中将字符串转换为布尔值?(How can I convert a string to boolean in JavaScript?)

Can I convert a string representing a boolean value (eg, 'true', 'false') into a intrinsic type in JavaScript?

(我可以将表示布尔值(例如“ true”,“ false”)的字符串转换为JavaScript中的固有类型吗?)

I have a hidden form in HTML that is updated based upon a user's selection within a list.

(我有一个隐藏的HTML表单,该表单会根据用户在列表中的选择进行更新。)

This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value.

(此表单包含一些表示布尔值的字段,并使用内部布尔值动态填充。)

However, once this value is placed into the hidden input field it becomes a string.

(但是,一旦将此值放入隐藏的输入字段中,它将成为一个字符串。)

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

(一旦将字段转换为字符串,我可以找到确定该字段的布尔值的唯一方法就是依赖其字符串表示形式的文字值。)

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

Is there a better way to accomplish this?

(有没有更好的方法可以做到这一点?)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do:(做:)

var isTrueSet = (myValue == 'true');

You could make it stricter by using the identity operator ( === ), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator ( == ).

(您可以通过使用标识运算符( === )来使其更严格,当比较的变量具有不同类型时,它不会进行任何隐式类型转换,而不是等于运算符( == )。)

var isTrueSet = (myValue === 'true');

Don't:(别:)

You should probably be cautious about using these two methods for your specific needs:

(您可能应谨慎使用这两种方法来满足您的特定需求:)

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

Any string which isn't the empty string will evaluate to true by using them.

(任何不是空字符串的字符串都将通过使用它们来评估为true 。)

Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.

(尽管它们是我可以想到的与布尔转换有关的最干净的方法,但我认为它们并不是您想要的。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...