开发者

What does this JS Expression mean?

What does this JS expression mean? What are we returning?

return dihy(year) in {353:1, 383:1}开发者_如何学运维;


This is a return statement that causes the containing function to return a Boolean value.

  1. It calls the function dihy() with the value of the variable year as its argument.
  2. It checks whether the return value is either 353 or 383 (the names of the properties that exist in the object literal). It does not matter what value the property has; it just needs to exist within the object. (That is, 1 is just an arbitrary value.)
  3. If so, the function returns true, otherwise false.

JavaScript programmers sometimes use this approach because it is shorter than checking against each value individually, and it is easy to programmatically add new values to check against:

var foo = {353: 1, 383: 1};

function bar(year) {
    return year in foo;
}

alert(bar(1955)); // false
foo[1955] = 1;
alert(bar(1955)); // true

You may want to look at the MDC documentation for the in operator.


It will be true if the call to the function dihy with the argument year is a key in the object {353:1, 383:1} and false otherwise.

It could be rewritten like this for example:

var result = dihy(year);
return result == 353 || result == 383;


This is an expression:

dihy(year) in {353:1, 383:1}

The dihy(year) function call presumably returns a Number value. If that value is either 353 or 383, the expression will evaluate to true, otherwise to false.

Note that your code is not an expression, but a statement, the return statement:

return expression; 

So, the return statement will either return true or false.


Returns true or false, depending is the result that dihy() returns 353 or 383 (true for those two, anything else is false).

And it means exactly that... is the result of this function contained in this data collection...


There is no reason to use an object here, i.e. {353: 1, 383: 1}. In fact, the values of 1 are confusing and can make the uninitiated think that the value of 1 is being returned when it is not and is purely arbitrary.

The following is equivalent:

dihy(year) in [353, 383]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜