Max length for a function parameter - javascript

Is there any max length for a JavaScript function() parameter?
I created a function which had a long parameter, but it didn't work. When I shortened the parameter of the same function, it worked. Does that mean that there is a maximum length for a function argument? If so, please recommend alternatives to my current method.
JavaScript
function example(idnum) {
alert(idnum);
}
HTML
<div onclick='example(*php variable,no special character included*)'></div>
When the PHP variable is long, such as "17b6f557969619544eb1e6cd58c3f341", it does not work. But if I change the variable to something like "203", the function works successfully.

"Douglas Crockford" wrote in message
news:9a027$3fa7c56d$44a4aebc$9152#msgid.meganewsse rvers.com...
[color=blue]
... . The maximum length with will be implementation-specific. ...[/color]
In microsoft.public.scripting.jscript, Michael Harris
(Microsoft.MVP.Scripting), who might be expected to know, quoted:-
In JScript,
variant string variables have the same limit as in VBScript, up to
2^31 characters.
String literals (as in "this is a literal") have (IIRC) a limit
~2^10 (1024) characters.
for the JScript implementation.
Blockquote

Sounds like you actually want to pass the PHP variable's value literally to the function, not as a variable name.
example(17b6f557969619544eb1e6cd58c3f341)
tries to call the function with that variable (likely causing an exception, or even being a syntax error), while
example(203)
calls the function with the number literal for the integer 203. If you want to pass the value as a string, use json_encode!
Also notice that you will need to escape everything for use in a HTML attribute (i.e. escape quotes, < and >), as you have
<div onclick=" [some code here] ">

Related

Javascript - Why use string as function name

I'm working on a dojo project and stumbled on code below:
format: function ( /*Date*/ value, /*locale.__FormatOptions*/ constraints) {
....
},
"parse": function ( /*String*/ value, /*locale.__FormatOptions*/ constraints) {
.....
},
As you can see parse method name is a string. I haven't seen something like this before. Is there any reason for doing this?
Link to original file.
According to JavaScript / ECMAScript standard, object property (or functions) identifiers (as used before the colon : in your example) can be any valid identifier (i.e. like the format without quotes), any string (like "parse") or even any number.
Using "parse" in that case is strictly equivalent as using parse, but that would have been different in the case for example of "parse that value", which is a valid string identifier for an object property, even though it has spaces!
Then you can use either myObject.parse or myObject["parse"] to access your property, whereas in my last example you have no choice but using myObject["parse that value"] to access it.
I think we should also mention a specific case where using quotes for object keys is different from without quotes: if you were to use Google Closure minifier in ADVANCED_OPTIMIZATIONS mode, it would replace any non-quoted identifier to try and save space, whereas it would leave intact quoted identifiers, as Google team took this as the indicator that you will try to access it later on with the square brackets method and string, or if you check the actual key name like this:
for (var i in myObject) {
if (i === "parse") { // if i is replaced by the minifier, you will never execute the block below
// do something...
}
}
This specificity which forces you to use quoted identifiers sometimes (but not always, if you do not need to keep the original name) is one of the reasons that push people not using this advanced optimizations mode.
I don't see any reason for using extra quotes.
JSON requires it, but your object literal is not JSON. ES3 required this for keywords, but parse never was a keyword.
In this particular case there is no reason to do that, but I've faced scenarios where I needed to use quotes to define elements. For example:
var httpHeadersToAdd= {
'User-Agent': 'whatever',
Date: new Date()
};
With no quotes the interpreter understands that your are trying to do a subtract operation with variables User and Agent and throws a syntax error SyntaxError: Unexpected token -. Same can be made with functions, and then you have to call them with brackets:
var obj= {
'my-function': function (){}
}
obj['my-function']();
Going back to the code you linked, maybe someone wrote that in a JSON-ish way because that's how JSON strings looks like (double quotes are mandatory in JSON, single quotes don't work)

Javascript function that converts unicode notation code to utf-8 in HTML

I follow the link How to convert javascript unicode notation code to utf-8? to run the function in my console.
function encode_utf8( s ){return unescape( encodeURIComponent( s ) );}( '\u4e0a\u6d77' )
Then I get:
"上海"
However, when I do this way:
foo = function(s){return unescape( encodeURIComponent( s ) );}
foo('\u4e0a\u6d77');
foo("\u4e0a\u6d77");
Then I get"ä¸æµ·" "ä¸æµ·"
What is wrong with the function? Thanks ahead.
EDIT:
I thank you guys' explanation. Now I find that you just need to directly input in Chrome console '\u4e0a\u6d77', then I will get "上海".
However my original problem is that I want to convert unicode code to utf-8 in the html file, not in console. I could not find the answer.
EDIT:
Again, I want to thank you guys.
Now I find that my problem is that I get string like '\\u4e0a\\u6d77' from txt file. (Note here there are two back slashes). How can I change it to '\u4e0a\u6d77' (I want to get rid of one back slash).
Now I know once you get '\u4e0a\u6d77' (only one back slash) and then HTML will automatically show it as "上海"
EDIT:
Now I find the solution: HERE
Your first one is a function declaration followed by an unrelated expression in parentheses containing a string literals. The function is never called. The end result of that in the console is the value of the expression within the parens, which is the value of the string '\u4e0a\u6d77', which is of course "上海".
Your second one first creates the function (via a function expression), then calls it (twice, for some reason), passing in that string, and shows the function's return value.
So you see a difference because in the first case, you never call the function, you just get back the same string you provided. In the second case, you actually call the function and get back the UTF-8 data.

Jmeter: Javascript variable not returning any value

I am using one Javascript function to generate a random Number.
Used a User Parameter(Preprocessor) under the request
Added a Variable: farmeid
Function: ${__javaScript('bam-'+parseInt((Math.random()*1000000),10))}
When I am using the varialble ${frameid}, it is returning no Value.
The problem is that there is a comma in your expression here: ),10 which acts as a delimiter for function parameters. If you can remove this ,10 bit so your expression could look like:
${__javaScript('bam-'+parseInt(Math.random()*1000000),)}
This would be successfully evaluated by __javaScript function.
If this 10 bit is a must you can use BSF PreProcessor with the following code:
vars.put("frameid",'bam-'+parseInt((Math.random()*1000000),10));
And the easiest way is using __Random function like
bam-${__Random(111111,999999,)}
directly where it's required.
Hope this helps.
It's better to use Jmeter's Random Variable generator.
http://jmeter.apache.org/usermanual/component_reference.html#Random_Variable
Cheers,

decode javascript sequence into python

I'm a beginner to Python trying to decode this javascript sequence. I'm not only a beginner in Python, I understand javascript even less :) I know i could put it into an online decoder such as this: http://coderstoolbox.net/string/ but I want to deal with it myself - more for practice than anything else... Im using Beautiful Soup to get the data, so I have its functions available for decoding.
If anyone can point me to equivalent functions in python I would appreciate it.
function encode(str){
var t=''; var s=unescape(str);
var x=Math.round(Math.sqrt(49));
for(var i=0;i<s.length;i++) t+=
String.fromCharCode(s.charCodeAt(i)^(i%2?x:0));
print(t);
}
This is my understanding of it so far:
i think I can use 'HTML entities in BS to unescape..?
the second one just seems to be a constant number ? square root of 49 rounded...
sets up the loop
this is the one i dont get. 1 i dont know what the fromCharCode function does. 2 not sure what the bit at the end is. looks like its getting a character code from i to the power something. i understand i is being modulo'd with 2 but what is the '?x:0' bit ? - how would you replicate this in Python ?
thanks for reading !
EDIT: is there a python library that can just run this code ? I've done this before with bash and used rhino, but the alternatives in Python seem a bit scary for a beginner, eg spidermonkey, etc...
1) the python equivalent to unescape is urllib.unquote() in python 2.x series and urllib.parse.unquote() in python 3.x series
2) you guess the simplest way to do it is to do x = 7
3) the simplest way to loop on string charters is to do for c in string: but to have the index you should do for i,c in enumerate(string):
4) the string.charChodeAt(c) is the same than chr(c)
finally I would duplicate the loop part as follow:
result = []
for i,c in enumerate(string):
result.append(chr(ord(c)^(x if i%2 else 0)))
print("".join(result))
in fact using a temporary array to make the appends is more efficient than happening to strings as the strings don't mutate
I don't know Python, but I can explain what is happening here so that you can rewrite in Python.
1) function encode is declared and not assigned, so in JavaScript it will get hoisted to the top of its parent function, if there is one.
2) Inside function encode there are 4 variables that will get hoisted to the top of function encode:
t, which is assigned to an empty string, which means 0 length but type is string
s, which is assigned of a value of the argument "str" that is passed through the unencode function. unencode just reverses a URI reserved character encoding.
x, which is of type number with a value of 7
i, which is assigned 0 and used as your loop iterator
3) The loop index starts at 0 and breaks no later than the index is the same size as the character length on variable s.
4) The loop is written in a sloppy manner without curly braces, so it terminates at the first line break, which means variable t is performing a string concat in reflection of variable s.
5) The next line beginning with the string object looks like it is supposed to be in loop, but its not, because this code is sloppy. It doesn't matter anyways because variable s is not really used for anything further.
6) A print function is used with variable t as its argument. Variable t should look identical to variable s, which is probably not what the original author of this code intended.
7) I have no idea what print is. Perhaps the original author meant something like alert or console.log instead of print.

correct function parameters designation

Every time i pass some parameters to a JavasScript or jQuery functon, i use some random letters. What are the correct letters for the corresponding variable types?
function(o){} for example is for a object. But what are the other letters? Do someone have a list of those?
I advise you not to assign names according to types but according to the data that the variable contain. If you pass an object that contains the configuration for a function call the variable configuration if you pass a variable that contains a name call it name and so on. In this way the code is more readable and understandable.
Any letter will do, there is no such thing as a standard for using letters as parameters.
However, using letters for parameters is bad practise, because a letter does not describe what the parameter is intended for.
Consider this example:
function ShowBusyCursor(s) {
//...
}
If you look at the function header, you cannot guess what the parameter s stands for. But if you change the code to this:
function ShowBusyCursor(cursorIsDisplayed) {
//...
}
The parameter cursorIsDisplayed is a lot more developer-friendly and tells you it's a boolean that can be set to true to display the cursor. If you used s, you would have to look into the code to figure that out.
Here is a good list of letters I could think of:
o - object
a - array
s - string
d - date
n - number
r - regexp
b - boolean
But seriously, jokes apart, I think you might be mixing up the packed/minified source with the actual source that developers write. For example, this little function looked like this originally:
function myFunction(personName) {
this.name = personName;
}
But after minifying, it becomes:
function myFunction(a){this.name=a}
packer is one such utility by Dean Edwards that will minify your Javascript. Play with your source code at this website and see the compressed output. Check the Shrink variables option on the right to see how parameters and other variables get renamed.
This however shouldn't affect how you write your code at all. Be it Javascript, or any other language, all identifiers - variables, function names, class names, etc. should be named after what they represent or do rather than obscure shorthands.
Re-iterating what mck89 said, it's better to go with explanatory variable names rather than just a letter for the type. What if you have more than one parameter of the same time, do you start appending numbers?
I have often seen explanatory variable names which include the type, for instance sFirstName would be a string denoted by the "s", bForce would be a boolean, oConfig would be an object and nSubTotal would be a number.
This is a variation of Hungarian notation, and I'd advise against using single-letter variable names. What if you need to pass in 2 of any one data type? Like others have said, it also doesn't represent the meaning of the variable very well. I think this is much better:
function foo(sFirstName, sLastName)
{
alert("Hi, my name is " + sFirstName + " " + sLastName);
}

Categories