ReferenceError: Can't find variable: sumArray - javascript

I keep getting an error message in my web page console when testing out this loop; "ReferenceError: Can't find variable: sumArray".
My first loop worked just fine and resulted in a "true" message.
//*** isUniform() ***
function isUniform(arr){
var first = arr[0];
for(var i = 1; i < arr.length; i++){
if(arr[i] !== first){
return false;
}
}
return true;
}
But my second loop worked just fine and resulted in a "ReferenceError: Can't find variable: sumArray" message.
// *** sumArray() ***
function sumArray(arr){
var total = 0;
arr.forEach(function(element){
total += element;
});
return total;
}

Related

getting error " TypeError: Found non-callable ##iterator " even though the array is inerrable

I'm using one of the online JS editor and it is giving me this below error although when I'm consoling the value of initial it is an array so it should iterate. I' not getting what is wrong with it. Thanks in advance for helping.
let lists = [[1,4,5],[1,3,4],[2,6]];
let output=[];
let initial = lists[0]?lists[0]:[]
output.push(...initial); //giving error here
for(let i=1; i<lists.length; i++) {
curr = output;
next = lists[i];
j=0;k=0;
x=0;
//console.log(j,next,'next')
while(j<next.length) {
if(next[j]<=curr[x]){
output.splice(x,0,next[j]);
j++;
x++;
}else{
if(curr.length>x){
//k++;
x++;
}else{
output.push(...next.slice(j))
break;
}
}
}
}
//console.log(output)

Uncaught TypeError: Cannot read property '0' of undefined in JavaScript Memory game

I have a problem with my JavaScript memory game, it's supposed to create some <div/> which will be responsible as a our memory game cards and the user can input before pressing the start button how much rows and columns he wants to have. But somehow I got an error saying: Uncaught TypeError: Cannot read property '0' of undefined. This is the code responsible for creating the div table and not only:
function GameBoard(n,m) {
this.n = n;
this.m = m;
score = 0;
//n*m%2==0
picBoard = new Array(n);
last = -1;
accepTab = new Array(n*m/2);
for (var i=0; i<accepTab.length; i++){
accepTab[i] = 0;
}
for (var i=0; i<picBoard.length; i++){
picBoard[i] = new Array(m);
for (var j=0; j<picBoard[i].length; j++){
picBoard[i][j] = new Picture(accepTab);
}
}
function getPicture(id) {
console.log(picBoard);
return picBoard[id[0]][id[1]].val
}
function show(obj){
val = getPicture(getId(obj.id));
$(obj).html(val);
if(last==-1){
last = val;
lastId = getId(obj.id);
} else {
if(last==val){
$('#score').html(++score);
} else {
setTimeout(function(){
$(obj).html("X");
$("#col"+lastId[0]+"_"+lastId[1]).html("X");
}, 1000);
}
last=-1;
}
}
for(var i=0; i<n; i++){
$("#board").append("<div class=row id=row"+i+"> ");
for(var j=0; j<m; j++){
$("#board #row"+i).append("<span class=col id=col"+i+"_"+j+">X");
$("#col"+i+"_"+j).bind("click", function() {
show(this);
});
}
}
}
and the Console is saying the problem is with the line of function getPicture with return picBoard[id[0]][id[1]].val. And the function for Starting the game
var board;
function start(){
var n = document.getElementById("rows").value;
var m = document.getElementById("cols").value;
board = new GameBoard(n,m);
sec=0;
$("#start").unbind("click");
}
Whenever I call the function GameBoard without n and m variables but instead of values like 3 and 4 everything is working fine, it's just the thing when I tried to give a user an option to choose how big he wants to have the table of memory cards.
n and m are strings, not numbers. So some of the operations you do will result in different things. So convert them to numbers
board = new GameBoard(+n,+m);

Javascript Memory Leak in for loop

When I run the following code in node.js I get the following error message:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory
//Running this code causes program to run out of memory.
for(var i = 0; i < files.length; i++){
readFile(files[i]);
}
//log each line of file to console
function readFile(data){
var lines = fs.readFileSync(data).toString().split('\n');
for(var k = 0; k < lines.length; k++){
console.log(lines[k]);
}
}
But, if I change the readFile function and take the console.log(lines[k]) out of the for loop, the fatal error goes away. Why is that? And how can I fix the original code so it stops running out of memory?
function readFile(data){
var lines = fs.readFileSync(data).toString().split('\n');
var string = ''
for(var k = 0; k < lines.length; k++){
//console.log(lines[k]);
string += lines[k];
}
console.log(string); //log the same string outside the loop and the fatal error goes away
}
do npm install async --save
var async = require('async');
async.eachSeries(files , filesIteration , finishIteration);
function filesIteration(file , callBack){
readFile(file , callBack);
}
function readFile(data , cb){
var lines = fs.readFileSync(data).toString().split('\n');
for(var k = 0; k < lines.length; k++){
console.log(lines[k]);
if(k === lines.length - 1){
cb();
}
}
}
function finishIteration(){
console.log('all files processed');
}

Count how many times a character happens in a string and store it in an array JavaScript

I've been trying to figure out how to count how many times a character happens in a string and store it in another variable that will hold the character and the number of times it occurs in the string.
For example:
var greeting = "Hello World";
[H] occurs [1] time.
[e] occurs [1] time.
[l] occurs [3] times.
[o] occurs [2] times.
[W] occurs [1] time.
[r] occurs [1] time.
[d] occurs [1] time.
I am a JS Beginner and I tried as much as I can following guides and tutorials but this exercise seems to be out of my league. I would appreciate some help as to how would you guys go on about solving this problem.
Thanks!
You basically want to create a mapped set of characters to it's count in the string. Storing this stuff in an array might be weird as you'd need 2 Dimentional arrays. Instead store it in an hash object.
var greeting = "Hello world!";
var hash = {};
for(var i = 0; i < greeting.length; i++){
if(hash[greeting[i]] === undefined){
hash[greeting[i]] = 1;
} else {
hash[greeting[i]] += 1;
}
}
// printing the stuff in hash.
for(var x in hash){
if(hash.hasOwnProperty(x)){
console.log(x, hash[x]);
}
}
Anyway if you need this stuff in array, you can put so:
var arr = [];
var i = 0;
for(var x in hash){
if(hash.hasOwnProperty(x)){
arr[i++] = [x, hash[x]];
}
}
for(var i = 0; i< arr.length; i++){
console.log(arr[i]);
}
But I wouldn't recommend it. You can see redundancy for yourself.
Try this:
var result = {};
Array.prototype.map.call('Hello world!', function(x) {
if (typeof result[x] == 'undefined') {
result[x] = 1;
} else {
result[x] += 1;
}
});
console.log(result);
var result = {};
Array.prototype.map.call('Hello world!', function(x) {
if (typeof result[x] == 'undefined') {
result[x] = 1;
} else {
result[x] += 1;
}
});
console.log(result);

Javascript TypeError: Array is undefined

to test some things in javascript I am building a small minesweeper.
The following code is the initialization of the two-dimension array P.field. Afterwards a number of random fields are getting filled with an x, symbolizing that there's a mine on this field.
P.field = new Array(num);
for (var i = 0; i < P.field.length; i++)
P.field[i] = new Array(num);
$.each(P.field, function(index, key) {
$.each(key, function(i, k) {
P.field[index][i] = '-';
});
});
var arr = [];
while (arr.length < 10) {
var found = false;
var randomnumber = Math.ceil(Math.random()*(num*num-1));
for (var i = 0; i < arr.length; i++)
if (arr[i] == randomnumber) { found = true; break; }
if (!found) arr[arr.length] = randomnumber;
}
for (var i = 0; i < arr.length; i++) {
P.field[ Math.floor(arr[i]/num) ][ Math.floor(arr[i]-Math.floor(arr[i]/num)*num)-1 ] = 'x';
}
However, in my algorithm for counting the mines in surrounding fields, I get the console error TypeError: P.field[(r+1)] is undefined. Every field (except of those from the last row) returns this error, which is something I can't quite understand.
P.field[rows][columns] has a length of 10 per dimension in my tests ([10][10]). When I try to get the value of P.field[9][0] to P.field[9][9] there's nothing wrong. However when I adress any smaller row, this exception kicks in (P.field[0 + 1][0], P.field[3 + 1][6], and what so ever)...
I hope someone can tell me why.
edit
More code:
onReady: function() {
$('#sweeper table').on('click', 'td', function(e) {
var row = $(this).parent().attr('class'); // Class represents the index of the array
var column = $(this).attr('class'); // Class represents the index of the array
P.openField(row, column, $(this));
});
},
openField: function(r, c, e) {
if ( P.field[r][c] == 'x' ) {
e.addClass('mine');
} else {
e.html( P.surroundingMineCount(r, c) );
e.addClass('opened');
}
},
surroundingMineCount: function(r, c) {
var count = 0;
if ( P.field[r][c-1] == 'x' ) count++;
if ( P.field[r-1][c-1] == 'x' ) count++;
if ( P.field[r][c+1] == 'x' ) count++;
if ( P.field[r-1][c] == 'x' ) count++;
if ( P.field[r-1][c+1] == 'x' ) count++;
if ( P.field[r+1][c] == 'x' ) count++;
if ( P.field[r+1][c-1] == 'x' ) count++;
return count;
},
Right now I have no validation if the r+1 or r-1 is actually a valid index for that array (I had one in, but removed it for testing). However that can't really be the error, because I even get errors in the middle of the table.
Looking at the code you've provided versus the errors you've had thrown, I'm skeptical about your suspected cause as the code used does indeed generate the correct set of arrays.
I suspect it may be a slightly simpler issue, the example generation code you've provided uses:
P.field = new Array(num);
which has P as a capital, whereas the error that you've had thrown uses it as lowercase:
TypeError: p.field[(r+1)] is undefined
Are you sure you haven't accidentally just used the incorrect case when testing?

Categories

Resources