There is a line of code in angular2.
this.id = +this.route.snapshot.params['id'];
What is the "+" means before "this.route.snapshot.params['id']"?
I also see "+" added before a folder name such as "+detail" in angular2-webpack-starter.
Do they have the same meaning?
Using + in Javascript is a quick way to cast a string to a number as long as the string is already in the form of an integer or float.
+'5000' // yields 5000
+'2.5' // yields 2.5
If the string contains any character that is not an integer (or decimal in the case of a float), this method will return NaN.
+'5n' // yields NaN
+'abcd' // yields NaN
enter image description here
In short if you put + operator in front of string which contains Number
then always get number other than that you will get NaN.
Related
This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 3 years ago.
Result shows "n.split is not a function" unless i include n=n+" " the following code.What does third line mean?
function reverse_a_number(n)
{
n = n + "";
return n.split("").reverse().join("");
}
console.log(reverse_a_number(32243));
There is no split function in Number.prototype. So, n = n + "" is just a simple way to convert a number to a string.
From the spec
If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
If one of the operands in an expression with + is a string, the other operand is also coerced to a string and concatenated with it
console.log( 1 + 1 ) // sum
console.log( 1 + "1" ) // concatenation
console.log( true + "string" ) // concatenation
In javascript , there is no Explicit declaration of datatype, by assigning value to the variable , it implicitly takes the datatype like int,string.
In your case,Simple you are applying String function to integer , so you are getting Error.
So first convert integer value into String by using "toString()" function.
Solution:
function reverse_a_number(n) {
//Casting
n=n.toString();
return Number(n.split("").reverse().join(""));
}
console.log(reverse_a_number(32243));
There is no split function for Number. You can do this as an alternate
+String.prototype.split.call(32243,'').reverse().join('')
What the above code does?
I am using split method in String class via context switching for number which returns array.
Then we are reversing the number and joining it.
Then unary plus converts it to number.
As #briosheje mentioned, you can also use the following
+[...''+32243].reverse().join('')
Cast the number to a string and then use split as numerical values don't have the split function. Again cast it to a number while returning
function reverse_a_number(n) {
n=n.toString();
return Number(n.split("").reverse().join(""));
}
console.log(reverse_a_number(32243));
The reason is that split method works only on string values and your passing integer value as argument, that's why it's working only after casting it to string
You can't split a number. By using n = n + "", you're casting it a string and then splitting it. However, you're also returning a string! You'll want to cast it back to an integer before you return it.
Hmm.. I think this could be solved easily.
turn the number to a string, this lets you turn it to an array
Split it to a array
use array's function 'reversed'
join it
turn it to an number or int again.
const number = 3211232;
const numberReversed = parseInt(number.toString().split("").reverse().join(""));
console.log(numberReversed);
I am new to JavaScript and currently understand two things about the parseInt() method:
parseInt("100") // gives 100
parseInt("2019#string") // gives 2019
However, why would parseInt("string#2019") give NaN?
You can see the issue if you look at the W3Schools page for parseInt:
If the first character cannot be converted to a number, parseInt() returns NaN.
This is why the following returns NaN:
console.log(parseInt("O123"));
But if you have multiple numbers in a string, separated by a non-digit character, then it will not error - it'll just return the first number:
Only the first number in the string is returned!
console.log(parseInt("12b34"));
This information is also found in the MDN page for parseInt:
If the first character cannot be converted to a number, NaN is returned.
The parseInt function takes in a string as an input, and tries to convert it to a number. Here are some examples that use parseInt to convert a string to a number. Your second example parseInt("string#2019") returns NaN because it string#2019 is not a valid type. Try just doing parseInt("2019").
You can read more about parseInt here.
Why does parseInt("-1000-500-75-33") return -1000?
Shouldn't it return the sum of those numbers: -1608
How can I get the string "-1000-500-75-33" to return as the sum of those numbers?
parseInt will try to get a number starting from the beginning of the string.
Since - is a valid character to begin a number with, it parses the string until it finds something invalid. The second - is invalid because no integer can contain an - inside it, only digits. So it stops there and considers the number to be "finished".
Now, if you want to process the expression, you can use eval like so:
eval("-1000-500-75-33")
This will return -1608 as expected.
parseInt will not perform any computations, rather it will try to convert a string into an integer. It returns -1000 because the dash afterwards would not be considered a valid number. If you want to sum all these numbers you could split on the dash, map to Number, then reduce:
var numString = "-1000-500-75-33";
numString.split('-').map(e => Number(e)).reduce((a, b) => a - b);
Try to eval! it's safe here
eval("-1000-500-75-33").toString()
console.log(eval("-1000-500-75-33").toString());
And about type casting: After parsing -1000, which is obviously "negative 1000", It will escape casting as soon as it detect a symbol common between numbers & strings. So parseInt is seeing "-1000-500-75-33" as "-1000NotConvertableString", So left the remaining away, returning -1000 as the result of type-casting.
Since they are in a string, ParseInt does not parse the whole string, just finds the first applicable number from the start & returns it. If the start of the string cannot be parsed, it returns NaN
parseInt("-1000NOT_NUMBER") = -1000
parseInt("test-1000`) = NaN
You have to use eval function to do what you want, that evaluates given string as if it were a command entered into the console;
eval("-1000-500-75-33") = -1608
I have the following two parseInt() and I am not quite sure why they gave me different results:
alert(parseInt(0.00001)) shows 0;
alert(parseInt(0.00000001)) shows 1
My guess is that since parseInt needs string parameter, it treats 0.00001 as ""+0.00001 which is "0.00001", therefore, the first alert will show 0 after parseInt. For the second statement, ""+0.00000001 will be "1e-8", whose parseInt will be 1. Am I correct?
Thanks
I believe you are correct.
parseInt(0.00001) == parseInt(String(0.00001)) == parseInt('0.00001') ==> 0
parseInt(0.00000001) == parseInt(String(0.00000001)) == parseInt('1e-8') ==> 1
You are correct.
parseInt is intended to get a number from a string. So, if you pass it a number, it first converts it into a string, and then back into a number. After string conversion, parseInt starts at the first number in the string and gives up at the first non-number related character. So "1.e-8" becomes "1"
If you know you are starting with a string, and are just trying to get an Integer value, you can do something like.
Math.round(Number('0.00000001')); // 0
If you know you have a floating point number and not a string...
Math.round(0.00000001); // 0
You can also truncate, ceil(), or floor the number
parseInt takes each character in the first argument (converted to a string) that it recognizes as a number, and as soon as it finds a non-numeric value it ignores that value and the rest of the string. (see MDN second paragraph under "Description")
Therefore it's likely that parseInt(0.00000001) === parseInt(String(0.00000001)) === parseInt("1e-8"), which would only extract the 1 from the string yielding parseInt("1") === 1
However, there's another possibility:
From Mozilla developer network:
parseInt(string, radix);
for the string argument (emphasis added): "The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored."
I think this possibility is less likely, since String(0.00000001) does not yield NAN.
I have this function (going trough the Eloquent Javascript Tutorial chapter 3):
function absolute(number) {
if (number < 0)
return -number;
else
return number;
}
show(absolute(prompt("Pick a number", "")));
If I run it and enter -3 the output will be 3 as expectet but if I enter just 3 the output will be "3" (with double quotes). I can get around by changing
return number;
to
return Number(number);
but why is that necessary? What am I missing?
prompt() always returns a string, but when you enter a negative number, it is handed to the -number call and implicitly converted to a Number. That doesn't happen if you pass it a positive, and the value received by prompt() is returned directly.
You can, as you discovered, cast it with Number(), or you can use parseInt(number, 10), or you could do -(-number) to flip it negative, then positive again, or more obviously as pointed out in comments, +number. (Don't do --number, which will cast it to a Number then decrement it)
Javascript is not strongly typed.
number comes from the prompt() function, which returns a string.
Since you aren't doing anything to change its type, it remains a string.
-number implicitly converts and returns an actual number.
If you have a string that needs to be converted to a number, please do the following:
var numString = '3';
var num = parseInt(numString);
console.log(num); // 3
JavaScript performs automatic conversion between types. Your incoming "number" is most likely string (you can verify by showing result of typeof(number)).
- does not take "string" as argument, so it will be converted to number first and than negated. You can get the same behavior using unary +: typeof(+ "3") is number when typeof("3") is string.
Same happens for binary - - will convert operands to number. + is more fun as it work with both strings "1"+"2" is "12", but 1+2 is 3.