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

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);

Related

user. and number later [duplicate]

This question already has answers here:
Can I get a javascript object property name that starts with a number?
(2 answers)
Closed 8 years ago.
I've got an object where one of the properties starts with a number. I've read that this was allowed, but I'm getting this error:
SyntaxError: identifier starts immediately after numeric literal
var stats = {"LOAD_AVG":{"1_MIN":0.08,"5_MIN":0.08,"15_MIN":0.08},"COUNTS":{"TOTAL":888,"RUNNING":1,"SLEEPING":887,"STOPPED":0,"ZOMBIE":0},"CPU":{"USER_CPU_TIME":8.9,"SYSTEM_CPU_TIME":2.4,"NICE_CPU_TIME":0,"IO_WAIT_TIME":1,"HARD_TIME":0,"SOFT_TIME":0.1,"STEAL_TIME":0},"MEMORY":{"PHYSICAL":{"TOTAL":"3921.98mb","IN_USE":"3682.652mb (93.9%)","AVAILABLE":"239.328mb (6.1%)","BUFFERS":"266.492mb (6.8%)"},"SWAP":{"TOTAL":"4194.296mb","IN_USE":"64.264mb (1.5%)","AVAILABLE":"4130.032mb (98.5%)","CACHE":"1191.328mb (28.4%)"}}};
//works fine
window.alert(stats.COUNTS.TOTAL);
//doesn't work
window.alert(stats.LOAD_AVG.1_MIN);
Here's a fiddle.
How can I access the properties that begin with a number without rewriting the PHP that generated it?
You can use bracket access for properties that aren't valid JavaScript identifiers, that goes for property names with spaces or other language symbols like +, *
window.alert(stats.LOAD_AVG["1_MIN"]);
You can use bracket access anywhere really
window.alert(stats["COUNTS"]["TOTAL"]);

convert the literal value with parentheses [duplicate]

This question already has answers here:
Calling member function of number literal
(3 answers)
Closed 3 years ago.
I'm new to Javascript, and I saw code like this:
var myData1 = (5).toString() + String(5);
and the author says he placed the numeric value in parentheses and then called the toString method. This is because you have to allow JavaScript to convert the literal value into a number before you can call the methods that the number type defines.
I'm confused, isn't that 5 is already a number, why 5 needs be converted as (5) to be a number?
The author is partly right. This has nothing todo with turning the literal into a number, this is just about a syntactical distinction: The. can either be used to express fractional numbers (1.1) or it can be used for property access (obj.prop). Now if you'd do:
1.toString()
that would be a syntax error, as the dot is treated as a number seperator. You could do one of the following to use the property access dot instead:
1.0.toString() // as the first dot is the number seperator already, the second dot must be property access
1..toString() // same here
(1).toString() // the dot is clearly not part of the number literal

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

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

JavaScript test if number variable is a number [duplicate]

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 5 years ago.
I’m loading a JSON file a reading the values into an array using a for loop
I’m concerned that sometimes the JSON file might become corrupted ie the values Im reading in might become ASCII letters ie 1t3 where the value should of been 123
Is there a test case where you could say if values[a] does not equal a number then set it to “ “ or blank
Thanks,
Ben
You could use the parseInt() function and check if it returns an integer or NaN. You can check out information on it on W3schools or the MDN Web Docs.
However, in my opinion, it would be better to use regular expressions. If you read the w3schools examples for parseInt(), they show that "0x10" is read as 16.
For a regular expression, try the following:
function isNumber(n) {
// Added checking for period (in the case of floats)
var validFloat = function () {
if (n.match(/[\.][0-9]/) === null || n.match(/[^0-9]/).length !== 1) {
return false;
} return true;
};
return n.match(/[^0-9]/) === null ? true : validFloat();
}
// Example Tests for Code Snippet
console.log(isNumber("993"));
console.log(isNumber("0t1"));
console.log(isNumber("02-0"));
console.log(isNumber("0291"));
console.log(isNumber("0x16"));
console.log(isNumber("8.97"));
The MDN Web Docs have a super helpful page on Regular Expressions.

Double dot syntax in JavaScript - What is this expression doing and how is it valid syntax? [duplicate]

This question already has answers here:
Why does 10..toString() work, but 10.toString() does not? [duplicate]
(3 answers)
Closed 8 years ago.
14.toString();
// Result -> SyntaxError: Unexpected token ILLEGAL
14..toString();
// Result -> "14"
What is placing an extra dot after the number doing, and how is this valid syntax?
14. is a Number. .toString() calls a method on that Number.
Thus 14..toString() is the same as 14.0.toString().
You couldn't have 14.toString() because the . is still the floating point and not the property accessing symbol.
It is important to remember that the parser is greedy.
It sees the 1, so it starts reading a number. 4 is valid in a number, . is valid in a number, t is not, so it stops.
So it has the number 14. (which is just 14). Now what to do with it? Uh... there's a t there, that's not valid, ERROR!
In the second case, . is valid in a number, . would be valid but we already have a dot so stop there.
We have 14. again, but this time when looking what to do it sees ., so it converts the 14. to a Number object, then calls toString() on it, result "14"
See also: Why does "a + + b" work, but "a++b" doesn't?

Categories

Resources