This question already has answers here:
Calling member function of number literal
(3 answers)
Closed 9 years ago.
I'm reading through Douglas Crockford's JavaScript: The Good Parts, and I'm at the point where he defines a fade function. Part of this code boils down to this:
var level = 1;
var hex = level.toString(16);
So I run this in my browser's console to see what I get....
var level = 1;
level.toString(16);
Hey, it returns "1"... Fabuloso! Wunderbar!
Then to be cheeky, I try this to see what I get...
1.toString(16);
And I get
SyntaxError: Unexpected token ILLEGAL
What the what? If level is a variable equal to 1, and running this method on level works fine, then why doesn't running this method on the actual number 1 work? I tried a similar experiment with the toPrecision() method and that worked fine in both cases. What's the issue here? Is this another one of those inherent flaws in the JavaScript implementation, or am I missing something? I am testing in Google Chrome.
Related: Stack Overflow question Why don't number literals have access to Number methods?.
It's just a language grammar limitation.
Since 1. is a legal literal number (and 1.t is not) the tokeniser will split this into the following tokens:
1.
toString
(
)
And that's an illegal sequence of tokens. It's object method, instead of object . method.
In the working versions in #Joey's answer, the braces prevent the tokenizer from treating the dot as part of the number literal instead of as a separate token, as does writing:
1.0.toString()
or
1..toString()
since the tokenizer knows that the second dot must be a token on its own, and not part of the number literal.
You need 1..toString or (1).toString to get the number literal
level is a variable (and thus an object).
1 is a literal. They are not objects and the interpreter thinks about them completely differently.
http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html#4
Related
This question already has answers here:
In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
(5 answers)
Closed 7 months ago.
I've seen somewhere written in the code fixture.componentInstance.dataSource!.data = [];
I want to know the meaning of dataSource!.data
I know about the meaning of question mark(?) before dot(.) like key1?.key2 but an Exclamation(!) before dot(.) !. expression makes me curious.
Many thanks in advance!!
It's called the Non-null Assertion Operator
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#non-null-assertion-operator-postfix-
It removes null and undefined, allowing you to assert that you know there will be a value. Usually this is a code smell, something that should give you pause to consider other methods so that you can avoid using it. Type narrowing would be preferred. But in some specific instances, this operator can be a useful tool.
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"]);
This question already has answers here:
javascript variable swapping using arrays
(3 answers)
Closed 8 years ago.
Saw in a single source next:
[param_o,param_got] = [param_got,param_o];
This code swap variables param_o & param_got.But how [param_o,param_got] = [param_got,param_o] works, if [] is new instance of Array in Javascript ?
EDIT
Try checking:
var param_o = 1;
var param_got = 2;
[param_o,param_got] = [param_got,param_o];
console.log(param_o+" "+param_got);
// 2 1
This notation is called destructuring assignment and is part of Javascript 1.7:
Destructuring assignment makes it possible to extract data from arrays
or objects using a syntax that mirrors the construction of array and
object literals.
The object and array literal expressions provide an easy way to create
ad-hoc packages of data. Once you've created these packages of data,
you can use them any way you want to. You can even return them from
functions.
One particularly useful thing you can do with destructuring assignment
is to read an entire structure in a single statement.
The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.
Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.
This question already has answers here:
How to convert string equation to number in javascript?
(5 answers)
Closed 8 years ago.
Is there any built-in function in JavaScript like eval built-in function in Python?
notice: eval function take an equation as string and returns result. for example assume variable x is 2, then eval("2x+5") returns 9.
Yes, there is eval function in JavaScript too.
Besides, the statement should be valid for evaluation, i.e. eval("2*x+5").
You should also note, that using eval in JavaScript is not recommended. You can read about at MDN.
REF: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval
Yes, it's called eval, oddly enough.
http://www.w3schools.com/jsref/jsref_eval.asp
Edit: the mozilla link from VisioN (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval) is better, since it explains why you shouldn't use it.
You can use eval() however you will need to convert any "human" math operators to ones understood by javascript.
var sum = "4x5";
eval(sum.replace("x", "*"));
Update didn't read the part about x being a variable! that does make it slightly more complicated depending on how complex the equations are.
This question already has answers here:
Why can't I access a property of an integer with a single dot?
(5 answers)
Closed 6 years ago.
56.toString not works throws exception . 56..toString works fine .
Can anyone explain what is the difference between these two statements ?
56.toString(); //throws exception
56..toString(); //Works Fine.
How it works?
Numeric literals are somewhat special, because the property access . can be conflated with a decimal point .
When the parser encounters 56. it expects a digit (or nothing) to follow this. When you write 56..toString() you are getting the toString() of 56.0
that's not problem for toString() method, just the 56. the toString will think it's 56.0, but it have not the '0', so it will fail.
work fine or like this:
(56.).toString()
or
56..toString()
The problem here is when you type
56.toString()
JavaScript thinks 56 is a variable name, and you are trying to access it's toString() method. But this doesn't work because 56 is not a variable, and it's not even a valid variable name, therefore results in a compile error. (Variable name must start with a letter)
Check here for JS variable naming rules
But when you add a dot behind the 56 (56.) it becomes a number literal, and language creates an instance of Number class for that, then tries to resolve toString() method on the Number instance. Since the Number class defines a method called toString() and then it works.
56..toString();
Is equivalent to
(new Number(56.)).toString();
Key to understand here is difference between Number literal (56.) and method access operator (variable.methodName() )