meaning of "[+" in Javascript or Angular [duplicate] - javascript

This question already has answers here:
What is the purpose of a plus symbol before a variable?
(4 answers)
Closed 3 years ago.
I am curious.
What is the meaning of [+ in this code:
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.product = products[+params.get('productId')];
});
}

Changes the string to integer/ number.
For example:
If you have "60". This is a string but if you add + front of it. This is a number now: 60
In your code, params.get('productId') returns string, and you might need it as number. It's short hand but it only convert numbers wrapped with string to number - not "one" to 1.
Also, [+. The first bracket is opening bracket for accessing element of the array based on index or element/ property of the object. For instance, products[5].
This is also called Unary plus (+),
+false // 0
+‘123’ // 123
+0xBABE // 47806 (Hexadecimal)
+null // 0
+function(val) {return val } // NaN
There is a detailed article if you are interested to read more on it:
https://medium.com/#nikjohn/cast-to-number-in-javascript-using-the-unary-operator-f4ca67c792ce

There is nothing related to Angular here.
This is the concept of Javascript, Basically It will change the value to number type (format).
While you pass your parameter in routing, by default it is in string format, in order to accept the same in integer format, generally follow this method.
For example -
new Date() // output Wed Sep 25 2019 00:35:05 GMT+0530 (India Standard Time)
+new Date() // output 1569351921895

[+ by itself doesn't mean anything, it's two separate things combined together.
The key piece is +params.get('productId'), which means "take the value of productId and force it into a numeric value." For instance, +"1" will become 1 as a number instead of a string, and +"foo" will become NaN.
Then the [ is just the opening bracket for the subscript notation.
For instance, if productId is "1", then it will reduce to products[1].

ngOnInit() {
this.route.paramMap.subscribe(params => {
this.product = products[+params.get('productId')]; // here [+params.get(productIs) ] returns you number with use of + operator and [+ means starting a bracket to map the array.
});
}
I hope you now understood the meaning.

implicit conversion of values from one data type to another, in this case from string to number.
https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion

Related

Convert Ordinal String to its number

I want to Convert Ordinal String to its number
e.g
"1st" to 1
"2nd" to 2
"3rd" to 3
...
Tried this function but return its ordinal, not the number
function nth(n){return["st","nd","rd"][((n+90)%100-10)%10-1]||"th"}
it should be the inverse of this function
just use parseInt
console.log(parseInt("1st"))
You can remove the last two characters because suffix has constant length.
function toNum(str) {
return parseInt(str.substring(0, str.length - 2));
}
console.log(toNum("1st"));
Simply Extract Numerical Values From The String using parseInt()
parseInt("1st");
This will extract 1 i.e. Integer from the String
You can also use the function match(...) with a Regular Expression /[0-9]+/.
console.log("3rd".match(/[0-9]+/)[0]) // -> 3
console.log("52381st".match(/[0-9]+/)[0]) // -> 52381
Just doing "3rd".match(/[0-9]+/) returns an object with a bit of useful data, but just accessing the property [0] will give you the output you're looking for (if you don't want to do parseInt like the other answers are mentioning haha).

eval() function in java script throwing error with direct value [duplicate]

This question already has answers here:
Why can't I access a property of an integer with a single dot?
(5 answers)
Closed 4 years ago.
I tried to evaluate string function toString() in console.
In one scenario it is working fine and in another scenario it is not working as expected.
Scenario 1:
eval(99.toString());
output:
Invalid or unexpected token ...
Scenario 2:
var a = 99;
eval(a.toString());
Output:
99
Please help me to understand the difference between both the scenarios.
That has nothing to do with eval.
The error is produced by 99.toString. The reason is that 99. is read as a number (equivalent to 99.0) and then toString is just a random word that doesn't fit the syntax:
99.0 toString // what the parser sees
To fix it, you need to keep . from being treated as part of the number. For example:
99 .toString() // numbers can't contain spaces, so '99' and '.' are read separately
(99).toString() // the ')' token prevents '.' from being read as part of the number
99.0.toString() // '99.0' is read as a number, then '.toString' is the property access
99..toString() // same as above, just with '99.' as the number
99['toString']() // using [ ] for property access, no '.' at all
A numeric literall (99) is not and object with properties. A variable with value 99 like var x = 99 is and object and you can use methods like x.toString()
eval expects a script input (string), in example:
var x = eval('var a = 99; a.toString()');
console.log(x);

parseInt not working with data from an Array created from a spitted Date inside Angularjs controller [duplicate]

This question already has answers here:
ToLocaleDateString() changes in IE11
(5 answers)
Closed 7 years ago.
I have a date that I am converting to LocaleDateString and then splitting it into an array inside an angulrajs controller. When I try to convert to int the elements in the array I get NaN. The characters in the array are numbers but the parse is not working.
How can I parse that data properly?
Code:
var dateLocal = $scope.startDate.toLocaleDateString(); //Has this ‎6‎/‎5‎/‎2015
var dateSplitted = dateLocal.split("/"); //Has [6,5,2015]
var month = parseInt(dateSplitted[0]); //HERE If I use parseIntI get NaN originally it has 6
var day = dateSplitted[1];//Has 5
var year = dateSplitted[2]; Has 2015
I want to be aple to convert to string month day and year.
You rely on toLocaleDateString, which is implementation dependent:
This function returns a String value. The contents of the String are
implementation-dependent
The problem is that your browser returns a string with some left-to-right marks (U+200E).
See the difference:
var str1 = "6", // "\u0036" <-- OK
str2 = "‎6‎"; // "\u200e\u0036\u200e" <-- Your "corrupted" string
parseInt(str1); // 6
parseInt(str2); // NaN
So you shouldn't trust the value returned by that method. Instead, use date methods to get the day, month and year.
This doesn't answer why you are getting NaN in your code, but instead of converting the date object to a string and parsing the parts, you can get the parts of the date directly using Date.prototype.getMonth(), Date.prototype.getDate() (day-of-month), and Date.prototype.getFullYear().
I tried out your code, and it seemed to work fine for me. For your dateLocal, I just replaced your value with var dateLocal = new Date().toLocaleDateString(); because I didn't know what value was loaded from your scope. When I did this, the code loaded fine, so you may want to double check the nature of the variable you are loading from the scope.

Why does parseFloat(027) equals 23 [duplicate]

This question already has answers here:
parseInt("010", 10); vs. parseInt(010, 10);
(2 answers)
Closed 8 years ago.
I tested it in the chrome console and also in IE11.
parseFloat(27) => 27
parseFloat('27') => 27
parseFloat('027') => 27
but
parseFloat(027) => 23
parseFloat(0027) => 23
I guess is understanding it as an octal, but I didn't find any reference to that here
Since I'm using it to secure a number which is a user input, how can I make certain that even with the preceding 0 it gets handled as a float?
"027" is the way you specify 27 octal in source code. Since you aren't going to let a user input your source code, there's nothing special you need to do.
parseFloat doesn't understand octal:
> parseFloat('027')
27
The problem is that you're feeding it a number, rather than a string. 027 is an octal numeric literal that evaluates to 23; parseFloat doesn't know it ever looked like 027. As long as you make sure to pass a string to the function, you shouldn't have any octal problems.
Why does parseFloat(027) equals 23
The argument to parseFloat() is a string value, so a cast is performed on anything that's not a string; literal numbers such as 0x20 or 027 are normalized to the decimal system first.
That means parseFloat(027) is actually parseFloat('23').
how can I make certain that even with the preceding 0 it gets handled as a float?
By making sure the value you're passing to parseFloat() is a string value, because leading zeroes have no special meaning in parseFloat() (and parseInt() with a radix of 10).
It's interpreting the input as octal. See here. If you enter '027' in the "Octal" field you'll see "23" output in the "Decimal" field.

What is the difference between Number(...) and parseFloat(...)

What is the difference between parseInt(string) and Number(string) in JavaScript has been asked previously.
But the answers basically focused on the radix and the ability of parseInt to take a string like "123htg" and turn it into 123.
What I am asking here is if there is any big difference between the returns of Number(...) and parseFloat(...) when you pass it an actual number string with no radix at all.
The internal workings are not that different, as #James Allardic already answered. There is a difference though. Using parseFloat, a (trimmed) string starting with one or more numeric characters followed by alphanumeric characters can convert to a Number, with Number that will not succeed. As in:
parseFloat('3.23abc'); //=> 3.23
Number('3.23abc'); //=> NaN
In both conversions, the input string is trimmed, by the way:
parseFloat(' 3.23abc '); //=> 3.23
Number(' 3.23 '); //=> 3.23
No. Both will result in the internal ToNumber(string) function being called.
From ES5 section 15.7.1 (The Number Constructor Called as a Function):
When Number is called as a function rather than as a constructor, it performs a type conversion...
Returns a Number value (not a Number object) computed by ToNumber(value) if value was supplied, else returns +0.
From ES5 section 15.1.2.3 (parseFloat (string)):
...
If neither trimmedString nor any prefix of trimmedString satisfies the syntax of a StrDecimalLiteral (see 9.3.1)
...
And 9.3.1 is the section titled "ToNumber Applied to the String Type", which is what the first quote is referring to when it says ToNumber(value).
Update (see comments)
By calling the Number constructor with the new operator, you will get an instance of the Number object, rather than a numeric literal. For example:
typeof new Number(10); //object
typeof Number(10); //number
This is defined in section 15.7.2 (The Number Constructor):
When Number is called as part of a new expression it is a constructor: it initialises the newly created object.
Not a whole lot of difference, as long as you're sure there's nothing but digits in your string. If there are, Number will return NaN. Another problem that you might get using the Number constructor is that co-workers might think you forgot the new keyword, and add it later on, causing strict comparisons to fail new Number(123) === 123 --> false whereas Number(123) === 123 --> true.
In general, I prefer to leave the Number constructor for what it is, and just use the shortest syntax there is to cast to an int/float: +numString, or use parse*.
When not using new to create a wrapper object for a numerical value, Number is relegated to simply doing type conversion from string to number.
'parseFloat' on the other hand, as you mentioned, can parse a floating point number from any string that starts with a digit, a decimal, or +/-
So, if you're only working with strings that contain only numerical values, Number(x) and parseFloat(x) will result in the same values
Please excuse me posting yet another answer, but I just got here via a Google search and did not find all of the details that I wanted. Running the following code in Node.js:
var vals = ["1", "1.1", "0", "1.1abc", "", " ", null];
for(var i = 0; i < vals.length; i++){
var ifTest = false;
if(vals[i])
{
ifTest = true;
}
console.log("val=" + vals[i] + ", Number()=" + Number(vals[i])+ ", parseFloat()=" + parseFloat(vals[i]) + ", if()=" + ifTest);
}
gives the following output:
val=1, Number()=1, parseFloat()=1, if()=true
val=1.1, Number()=1.1, parseFloat()=1.1, if()=true
val=0, Number()=0, parseFloat()=0, if()=true
val=1.1abc, Number()=NaN, parseFloat()=1.1, if()=true
val=, Number()=0, parseFloat()=NaN, if()=false
val= , Number()=0, parseFloat()=NaN, if()=true
val=null, Number()=0, parseFloat()=NaN, if()=false
Some noteworthy takeaways:
If protecting with an if(val) before trying to convert to number, then parseFloat() will return a number except in the whitespace case.
Number returns a number in all cases except for non-numeric characters aside from white-space.
Please feel free to add any test cases that I may be missing.

Categories

Resources