Вопрос

Can someone explain to me this JS shorthand code:

   navigator.sayswho = (function(){
      var N= navigator.appName, ua= navigator.userAgent, tem;
      var M= ua.match(/(opera|chrome|safari|firefox|msie|Trident)\/?\s*(\.?\d+(\.\d+)*)/i);
      if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
      M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
      return M;
   })();

The code is working, but I can't understand how it is working, especially this line:

M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
Это было полезно?

Решение

This:

M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];

means:

if (M)
  M = [M[1], M[2]];
else
  M = [N, navigator.appVersion, '-?'];

More verbosely, it checks to see if "M" is non-empty, which in this case means that the useragent regex matched the actual useragent string. If it's set, then it resets "M" to a new array; effectively it just drops the zeroth element of the original "M".

If it's not set, it creates a "fake" array from the application name, the version string, and what appears to be a marker string to indicate that it's an unrecognized useragent.

Другие советы

M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];

here M is boolean type variable contains true or false

i.e.

if(M)
   M = [M[1], M[2]];
else
   M = [N, navigator.appVersion,'-?'];
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top