开发者

adding chr to the number Prototype

开发者 https://www.devze.com 2023-03-10 19:03 出处:网络
I have the following function: var chr = function(X) { return String.fromCharCode(X) } But I would like to use i.开发者_StackOverflow社区chr() instead of chr(i).

I have the following function:

var chr = function(X) {
   return String.fromCharCode(X)
}

But I would like to use i.开发者_StackOverflow社区chr() instead of chr(i).

Q: How do I add chr() to the number prototype?


Number.prototype.chr = function() {
   return String.fromCharCode(this);
}

var n = 33;
console.log(n.chr());

http://jsfiddle.net/CXWeV/

Also, as Bryan points out, the following will work:

console.log((33).chr());
console.log(Number(33).chr());

But, the following does not work:

33.chr();

EDIT: Although, as Gumbo points out, this does:

33..chr();

As well as a check if the property already exists (see Erik's answer for another way to check):

if (!Number.prototype.chr) {
    Number.prototype.chr = function() {
       return String.fromCharCode(this);
    }
}


if (!Number.prototype.hasOwnProperty('chr')) {
   Number.prototype.chr = function() {
      return String.fromCharCode(this);
   };
}

To use this the number must be in a variable or wrapped in parentheses. Be aware that converting a scalar number to a Number object (called boxing) has an overhead. If you are doing the conversion repeatedly on the same value, you'll want to explicitly convert it to an object first with Number().

Note that simply doing String.fromCharCode might be easier or more clear in some situations.


The normal way, really. Note the importance of surrounding the number in parentheses (or storing it in a variable), as a dot would normally indicate a decimal point:

Number.prototype.chr = function () {
  return String.fromCharCode(this);
}

alert((97).chr()); // alerts "a"

I'm not sure whether this works in all browsers, but I'm assuming it does.

Interactive Example

0

精彩评论

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

关注公众号