i am read the source code of node(v0.10.33), in the file buffer.js
, i find this functiuon:
SlowBuffer.prototype.toString = function(encoding, start, end) {
encoding = String(encoding || 'utf8').toLowerCase();
start = +start || 0;
if (typeof end !== 'number') end = this.length;
// Fastpath empty strings
if (+end == start) {
return '';
}
switch (encoding) {
case 'hex':
return this.hexSlice(start, end);
case 'utf8':
case 'utf-8':
return this.utf8Slice(start, end);
case 'ascii':
return this.asciiSlice(start, end);
case 'binary':
return this.binarySlice(start, end);
case 'base64':
return this.base64Slice(start, end);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return this.ucs2Slice(start, end);
default:
throw new TypeError('Unknown encoding: ' + encoding);
}
};
But i don't understand this line's meaning: start = +start || 0;
, what's the purpose of +
before start
?
Here is the answer: The + and - operators also have unary versions, where they operate only on one variable. When used in this fashion, + returns the number representation of the object, while - returns its negative counterpart.
var a = "1";
var b = a; // b = "1": a string
var c = +a; // c = 1: a number
var d = -a; // d = -1: a number
+
is also used as the string concatenation operator: If any of its arguments is a string or is otherwise not a number, any non-string arguments are converted to strings, and the 2 strings are concatenated. For example, 5 + [1, 2, 3] evaluates to the string "51, 2, 3". More usefully, str1 + " " + str2 returns str1 concatenated with str2, with a space between.