Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is what is called <em>boxing</em>. If you have a primitive value and then call a method on that value, it will be wrapped as an object of the type <code>String</code>, <code>Number</code>, <code>Boolean</code>, or what have you. This is equivalent to calling <code>new String('a')</code>, for instance. (It is documented in <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.3" rel="nofollow">the ECMAScript specification</a>.)</p> <p><code>new String('a')</code> is not the same as <code>'a'</code>. It therefore is not found in the array.</p> <p>What you need to do, therefore, is convert the value back into the primitive value. You can always accomplish this with the <code>valueOf</code> method:</p> <pre><code>return vowels.indexOf(this.valueOf()) !== -1; </code></pre> <p>Your method is to call <code>this[0]</code>. This works, because it gets the first character from the string as a primitive, which is then found in the string. The downside is that <code>ab</code> would also be considered a vowel by this method.</p> <hr> <p>Similarly with numbers:</p> <pre><code> Number.prototype.is5 = function () { return this.valueOf() === 5; }; </code></pre> <hr> <p>One other point: this is the default behaviour of Javascript. It is not obvious or intuitive, as you have shown. In ECMAScript 5, "strict mode" was created, where all kinds of undesirable behaviours are disabled. Auto-boxing is one of them. So, if you use a modern browser, this will have the expected behaviour:</p> <pre><code>Number.prototype.is5 = function () { "use strict"; return this === 5; }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload