Parse boolean values in strings for use with Function.apply

旧巷老猫 提交于 2019-12-11 17:17:14

问题


I'm using String.split to parse a command line string into an array of strings. The result is then used to call a function using the Function.apply API.

If apply(null, ["17"]) is called with this function:

static function test(foo:int):void
{
    trace(foo, typeof(foo));
}

it works as expected (output: 17 number).

However, calling apply(null, ["false"]) or apply(null, ["0"]) with this function:

static function test(foo:Boolean):void
{
    trace(foo, typeof(foo));
}

does not work (expected output: false Boolean; actual output: true Boolean).

Is there a way to make it recognize "true" and "false" (or anything else) as Boolean values, just like it does with numerical strings? Ideally "true" and "false" should also remain valid string values.


回答1:


No, there is no built in way to interpret the strings "true" and "false" as booleans.

In ActionScript, and other ECMA script languages, the only string value that gets evaluated as boolean false is an empty string, "". Any string with a length gets evaluated as true in a boolean expression, including the strings "false" and "0".

In practice, this is seldom a big problem, since it is quite easy to make a string comparison. A bunch of suggestions here: How can I convert a string to boolean in JavaScript?



来源:https://stackoverflow.com/questions/2437902/parse-boolean-values-in-strings-for-use-with-function-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!