Buggy Javascript Function Complains Missing For Loop ")" - javascript

The following is my simple function to create a range array between two numbers. The problem is that console keeps complaining that for loop has a missing bracket ")" but I can plainly see that it is not missing. Please help!
function range(start, end){
var len = end - start;
for (var i = 0; i <= len; i++){
var arr[i] = x + i;
}
return arr[];
}
console.log(range(1, 10));
console.log(arr.length);
Here is the output:
SyntaxError: missing ) after for-loop control (line 3)
Edit
for (var i = 0; i <= len; i++){
was
for (var i = 0; i <= len; i++;){

remove
↓
for (var i = 0; i <= len; i++;)
Remove the final semicolon:
for (var i = 0; i <= len; i++)
Your code has other issues, but this answers the question asked. I suggest you pull out a guide on JavaScript and correct your syntax throughout your code.

There were three errors. I cannot fix undeclared 'x', which is either in outter scope (global) or this is an error that you have to fix with your own logic.
function range(start, end){
var arr = []; //declare your array
var len = end - start;
for (var i = 0; i <= len; i++){
arr[i] = x + i; //here x is undeclared, single array indices cannot be declared this way
}
return arr;
}
console.log(range(1, 10));
console.log(arr.length);

You shouldn't put a semi-colon (;) after the last statment in the for loop. Remove it.
It's very unlikely that something like a for loop is buggy in JavaScript, in a language that is usef by millions every day.

Related

JavaScript trim character

I want to delete "()" from each value. How would I do that?
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
console.log(arr[i]);
}
Since all the other answers are unnecessarily complicated, here's a simple one:
arr = arr.map(s => s.slice(1, -1));
You can do it in-place too if you prefer; the important part is .slice(1, -1), which takes a substring starting from the character at index 1 (the second character) and ending before the last character (-1).
String.prototype.slice documentation on MDN
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
var arrLength = arr[i].length -2;
var shortArr = arr[i].substr(1,arrLength);
console.log(shortArr);
}
This gets one character less on the front and back
use replace
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
var x = arr[i];
x = x.replace(/[()]/g,"");
console.log(x);
}
note:
i dedited, because alexander was right
so u need to use regex, "g" for search globally,
"[" "]" to find all character inside
This is fast and should work no matter how many parenthesis are in the string, it will remove them all.
arr[i] = arr[i].split(/\(|\)/g).join("");
This matches ( followed by anything that isn't ) followed by ). Would also fail for "(test(ing)123)", (if you care)
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++) {
arr[i] = arr[i].replace(/\(([^)]+)\)/g, "$1");
}
This is much more simple/faster (but arguably more brittle):
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++) {
arr[i] = arr[i].substr(1, arr[i].length - 2);
}

Why do I get "Uncaught TypeError: Cannot read property 'length' of undefined(…)"?

Error Message: Uncaught TypeError: Cannot read property 'length' of undefined(…)
Line 44, Column 23
I have read every post I can find related to this error but have not found anything applicable to this situation.
I'm trying to take a string and turn it into an array of arrays that is formatted to take the shape of steps (codewars' kata); one word across, next word down and so on. The problem I'm running into is that I keep getting an Uncaught TypeError: Cannot read property 'length' of undefined(…) when trying to use the length of an array element within a for loop. So in this nested loop:
for(var i = 0; i < masterStringOdd.length; i++){
temp2 = proArr.slice(0);
start2 = even[i].length - 1;
for(let j = 0; j < odd[i].length; j++){
let replace2 = masterStringOdd.charAt(i);
Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
finalOdd.push(temp2);
}
start2 += even[i+1].length - 1;
}
With the last line "start2 += even[i+1].length - 1;" (I have tried about a thousand different various of this) I get the error, but if I return that line "return even[i+1].length - 1;" I get 5, which is the correct length. My complete code is at the end of this email if anyone wants to look at it, and believe me I understand it is ridiculous and awkward (working code and completely unpolished) - skills at hand and all that.
Just can't figure out why I can't get and use the value of the element's length in this case. Any help would be greatly, greatly appreciated.
function wordStep(str) {
let array = str.split(" ");
let even = [], odd = [], proArr = [], finalEven = [], finalOdd = [];
//for loop to create sperate arrays for across and down
for (let i = 0; i < array.length; i++){
if (i%2 === 0){
even.push(array[i]);
} else {
odd.push(array[i].slice(1,-1));
}
}
//data collection and tool variables, might delete them if the are not needed
let finalLength = even.join("").toString().length - (even.length - 1);
let masterStringEven = even.join("").toString();
let yAxis = odd.join("").toString().length;
let masterStringOdd = odd.join("").toString();
//for loop to create protype array
for (let i = 0; i < finalLength; i++){
proArr.push(",");
}
// for loop to create final evens arrays
let start = 0;
for(let i = 0; i < even.length; i++){
let temp1 = proArr.slice(0);
let replace = even[i].split("");
Array.prototype.splice.apply(temp1, [start, replace.length].concat(replace));
finalEven.push(temp1);
start += replace.length-1;;
}
// nested loops for final odds' array
let temp2 = []
let start2 = 0;
for(var i = 0; i < masterStringOdd.length; i++){
temp2 = proArr.slice(0);
start2 = even[i].length - 1;
for(let j = 0; j < odd[i].length; j++){
let replace2 = masterStringOdd.charAt(i);
Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
finalOdd.push(temp2);
}
start2 += even[i+1].length - 1;
}
}
Fundamentally, what's happening is that you're going past the end of the even array, so even[i] gives you undefined, and then you try to read the length of undefined, which causes the error.
And indeed, we can see that in this loop:
for(var i = 0; i < masterStringOdd.length; i++){
temp2 = proArr.slice(0);
start2 = even[i].length - 1;
for(let j = 0; j < odd[i].length; j++){
let replace2 = masterStringOdd.charAt(i);
Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
finalOdd.push(temp2);
}
start2 += even[i+1].length - 1;
}
...you're assuming that masterStringOdd.length will always be less than even.length. Nothing in the code ensures this, and in fact it will frequently not be true. masterStringOdd.length is the length of the odd array's entries joined together as a string; even.length is the number of even entries. So there are two reasons why even.length may not be at least as big as masterStringOdd.length: 1. The latter is the length of a string, not an array; and 2. The latter relates to odd, not even.
The issue with your code is that you are not checking the even and odd arrays length before accessing them. This will create issue if you have str value in wordStep(str) which do not push values in these array at the indices where you are accessing those.
Put proper array length check for accessing the array at the particular index.
for(var i = 0; i < masterStringOdd.length; i++){
temp2 = proArr.slice(0);
if(even.legth > i)
start2 = even[i].length - 1;
if(odd.length > i){
for(let j = 0; j < odd[i].length; j++){
let replace2 = masterStringOdd.charAt(i);
Array.prototype.splice.apply(temp2, [start2, 1].concat(replace2));
finalOdd.push(temp2);
}
}
if(even.length > i +1)
{
console.log(even.length);
start2 += even[i+1].length - 1;
}
}
for example wordStep("Life is good for us"); this call will fill the array properly and you will not get any error.
but if its wordStep("Life Good");, you will see the issue in your code if proper length check are not applied
plunker to verify : http://plnkr.co/edit/QQovAAzlDhXgucikCGAb?p=preview

Javascript for loop without recalculating array's length

In my Javascript reference book, for loops are optimized in the following way:
for( var i = 0, len = keys.length; i < len; i + +) { BODY }
Apparently, doing "len = keys.length" prevents the computer from recalculating keys.length each time it goes through the for loop.
I don't understand why the book doesn't write "var len = keys.length" instead of "len = keys.length"? Isn't the book making "len" a global variable, which isn't good if you're trying to nest two for-loops that loop through two arrays?
E.g.
for( var i = 0, len = keys.length; i < len; i + +) {
for (var i = 0; len = array2.length; i < len; i++) {
}
}
Source: Flanagan, David (2011-04-18). JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides) (Kindle Locations 6992-6998). O'Reilly Media. Kindle Edition.
You can chain variable declarations like this
var i = 0, foo="bar", hello = "world"
Which is close to the same thing as
var i = 0;
var foo = "bar";
var hello = "world";
So this
for(var i = 0, len = keys.length; i < len; i++)
Is the same as
var len = keys.length;
for(var i = 0; i < len; i++)
I like to avoid .length altogether and use something like
var keys = /* array or nodelist */, key, i;
for(i = 0; key = keys[i]; i++)
This will cause the for loop to end as soon as key resolves to undefined.
Now you can use key instead of keys[i]
As a side note, your second example would never work as all of the variables defined in the first for statement would be overwritten by the second, yielding unexpected results. You can nest for loops, but you have to use different variable names.
AS Ankit correctly mentioned in the comments of the question, it is a shorthand. And moreover, if I am correct, javascript is functionally scoped and not block scoped, so you are overwriting the len declared in the outer for loop while re-declaring it in the inner one.
In Javascript each time you instantiate it's a heavy cost. Using one var and short hand commas to create multiple variables is much more efficient.
Your example using only one var to create a variable.
for (var i = 0, len = array2.length; i < len; i++) {
//loop
}
The alternative is to var up the len variable outside the loop.
var len = array2.length;
for (var i = 0; i < len; i++) {
//loop
}
Now you have two separate "var" instances.
I personally like to declare my var at the beginning.
var len = array2.length,
i = 0;
for(i = 0; i < len; i++){
//First loop
}
//So if I use more than one for loop in a routine I can just reuse i
for(i = 0; i < 10; i++){
//Second loop
}
Hope that helps explain.

undefined is returned in JavaScript function

When I call this function, sending for example: abc as the parameter,
the function returns: undefinedcba. I can't figure out why it's adding
'undefined' to my returned value. I'm probably overlooking something obvious
but I can't spot it. Thank you.
function FirstReverse(str) {
var str_arr1 = new Array();
var ans = '';
for(i=0; i < str.length; i++) {
str_arr1.push(str.charAt(i));
}
for(j=str.length; j >= 0; j--) {
ans += str_arr1[j];
}
return ans;
}
Strings are 0-indexed. str[str.length] does not exist.
j needs to start at str.length - 1.
Or, just return str_arr1.join();
The index of the string starts at 0, so string.length is always one number bigger than index of the last character in the string.
In the second for loop, use
for(var j=str.length -1; j >= 0; j--) {
The error is in the second for statement. See the solution:
function FirstReverse(str) {
var str_arr1 = new Array();
var ans = '';
for(i=0; i < str.length; i++) {
str_arr1.push(str.charAt(i));
}
for(j=str.length-1; j >= 0; j--) {
ans += str_arr1[j];
}
return ans;
}
Because when you pass 'abc' there are only 3 characters in it.
So arrray str_arr have elements at index 0, 1 and 2.
But you are looping for str.length i.e. for 3 times and str_arr[3] is not defined.
You should do this,
function FirstReverse(str) {
var str_arr1 = new Array();
var ans = '';
for(i=0; i < str.length; i++) {
str_arr1.push(str.charAt(i));
}
for(j=str.length-1; j >= 0; j--) {
ans += str_arr1[j];
}
return ans;
}
Looks like you want to reverse a string, which you can do in this javascript one liner
function reverse(s){
return s.split("").reverse().join("");
}
The reason you are getting an undefined is because your j starts with str.length, whereas it should be str.length-1. str_arr1[str.length] is out of bounds and therefore will be undefined.

setting a variable to each element of an array

i have function:
function getFieldNames(arrayOfRecords) {
var theStuff;
for (var i = 0; i = arrayOfRecords.length - 1; i++){
theStuff = arrayOfRecords[i];
theList = theStuff.split('" ');
for (var j = 0; j = theList.length - 1; j++) {
var v = theList[j].split('="');
fName1[i][j] = v[0];
}
}
return fName1;
}
the argument arrayOfRecords is an array, and i dont know how to setup to the 'theStuff' variable an array element? When I do like it is above, i get something stupid.
can anyone help me? :)
There may be other problems but the one that leaps out at me is your for loop header:
for (var i = 0; i = arrayOfRecords.length - 1; i++)
The second part should be a condition, which when evaluated to false will stop the loop from running. What you probably wanted was:
for (var i = 0; i < arrayOfRecords.length; i++)
So when i is not less than arrayOfRecords.length, the loop will stop. Alternatively (to keep the - 1, but I tend to use the above version):
for (var i = 0; i <= arrayOfRecords.length - 1; i++)
The same goes for the nested loop.

Categories