开发者

What does the || mean in this suitation?

开发者 https://www.devze.com 2023-03-22 05:43 出处:网络
Typically, |开发者_运维技巧| means or, but what does it mean in this case: function getCharCount ( e,s ) {

Typically, |开发者_运维技巧| means or, but what does it mean in this case:

function getCharCount ( e,s ) {
    s = s || ",";
    return getInnerText(e).split(s).length;
}      


s = s || ","

It's the default parameter option. If s is "falsey" s will be set to ","

So if s is an "" or undefined it will have a useful default.


That a way to define optional parameters in Javascript.

You can call this function with only 1 param...


Raynos has provided the answer, but there is more to add to describing this.

s = s || ",";

If s is any falsey value such as undefined, null, 0, false, NaN, "", etc..., then s will get initialized to be ",".

This can be very useful for initializing optional parameters to a function or for guaranteeing that parameters have at least some initial value. One does have to be very careful how it is used because this construct prohibits purposely passing a falsey value for the parameter s.

In this example, you can't pass an empty string for the value of s because it will be changed into ",". That's OK in this function, but maybe not in others. In other types of functions, you wouldn't be able to pass false which might be an allowable value.

If one only wants to protect against the parameter not being passed, then you have to use something like this which explicitly tests for undefined and allows the passing of other falsey values:

s = typeof s != "undefined" ? s : ',';    // if s is undefined, initialize

or if you want to validate that it was a string and allow an empty string, you could use:

s = typeof s == "string" ? s : ',';       // if s not a string, initalize


It means that s, if it's null, gets assigned the value ","; if s is not null, it retains its value.


s is s, or if s is not defined ( you did not pass the argument in the function call ), it's ","


sometimes , you dont know if a variable will ahve a value so you are telling your self that you have to have a value.

if if theres no value ( null) so youll have your own default value.

that what you wrote

 s = s || ",";

i dont know if s has value or not , but if not so put the ',' value.

0

精彩评论

暂无评论...
验证码 换一张
取 消