Im using the code below to try and find the first repeating character in a sequence. When I run the code in my browser, and stop it in the console at the letterArray.forEach function, console log error says my inputs to forEach are undefined. But it seems to me like forEach should just be taking the inputs from letterArray one at a time, seeing if they equal one, and return the result. Anybody know why it says my forEach loop cant read the inputs from my letterArray?
function firstNotRepeatingCharacter(string) {
var letterArray = [];
letterArray['a'] = 0;
letterArray['b'] = 0;
letterArray['c'] = 0;
letterArray['d'] = 0;
letterArray['e'] = 0;
letterArray['f'] = 0;
letterArray['g'] = 0;
letterArray['h'] = 0;
letterArray['i'] = 0;
letterArray['j'] = 0;
letterArray['k'] = 0;
letterArray['l'] = 0;
letterArray['m'] = 0;
letterArray['n'] = 0;
letterArray['o'] = 0;
letterArray['p'] = 0;
letterArray['q'] = 0;
letterArray['r'] = 0;
letterArray['s'] = 0;
letterArray['t'] = 0;
letterArray['u'] = 0;
letterArray['v'] = 0;
letterArray['w'] = 0;
letterArray['x'] = 0;
letterArray['y'] = 0;
letterArray['z'] = 0;
for(var letter of string) {
letterArray[letter] = letterArray[letter] + 1;
}
letterArray.forEach(function(value, index, thearay) {
if (value == 1) {
console.log(index);
}
});
}
var tester = "abacabad";
firstNotRepeatingCharacter(tester);
The minimal changes to your code required are as follows (see the comments // ****** in the code)
function firstNotRepeatingCharacter(string) {
// *********** change to Object
var letterArray = {};
letterArray['a'] = 0;
letterArray['b'] = 0;
letterArray['c'] = 0;
letterArray['d'] = 0;
letterArray['e'] = 0;
letterArray['f'] = 0;
letterArray['g'] = 0;
letterArray['h'] = 0;
letterArray['i'] = 0;
letterArray['j'] = 0;
letterArray['k'] = 0;
letterArray['l'] = 0;
letterArray['m'] = 0;
letterArray['n'] = 0;
letterArray['o'] = 0;
letterArray['p'] = 0;
letterArray['q'] = 0;
letterArray['r'] = 0;
letterArray['s'] = 0;
letterArray['t'] = 0;
letterArray['u'] = 0;
letterArray['v'] = 0;
letterArray['w'] = 0;
letterArray['x'] = 0;
letterArray['y'] = 0;
letterArray['z'] = 0;
for(var letter of string) {
letterArray[letter] = letterArray[letter] + 1;
}
// *********** an object has no forEach,
// so, we now need to iterate through the keys
// (a,b,c ...) of the object,
// that's where Object.keys helps
Object.keys(letterArray).forEach(function(key, index, thearay) {
var value = letterArray[key]; //the value is letterArray[key]
if (value == 1) {
console.log(key);
}
});
}
var tester = "abacabad";
firstNotRepeatingCharacter(tester);
However, looking at the name of the function, I would expect
firstNotRepeatingCharacter("abacabad"); // c
firstNotRepeatingCharacter("abadacad"); // d
If so, the code would be far simpler
function firstNotRepeatingCharacter(string) {
for (let i = 0; i < string.length; i++) {
if (string.split(string[i]).length == 2) {
return string[i];
}
}
return null;
}
console.log(firstNotRepeatingCharacter("abacadab"));
console.log(firstNotRepeatingCharacter("abadacab"));
Related
I wrote this code but it seems to keep printing out seal onto the console? Is there another ways to print the correct answer using arrays?
//i.stack.imgur.com/i8D8q.png
var items = "a=65/b=923/c=76/d=896/e=1/f=64/g=945/h=203/i=66";
function proto (thisone, order) {
proto[order] = thisone;
}
function proto2(thisone) {
proto2[thisone.split("=")[0]] = thisone.split("=")[1];
}
function animalMax (value, order2) {
if (!proto2[value.split("=")[0]]) {
proto(value, order2);
} else {
proto("null=-1", order2);
}
for (var y = 0; y < sp.length; y++) {
if (sp[y].split("=")[1] > Number(proto[order2].split("=")[1]) && !proto2[sp[y].split("=")[0]]) {
proto(sp[y], order2);
}
}
}
var sp = items.split("/");
for (var i = 0; i < sp.length; i++) {
animalMax(sp[i], i);
proto2(proto[i]);
}
var final = "";
for (var p = 0; p < sp.length; p++) {
final += proto[p];
}
console.log(final);
I am making a Conway Game of Life that it starts with a predefined board, I made that board through an two dimensional Array, have implemented the rules and they seem to be working, the problem is that the different generations just appear next to previous one without replacing it (see image [1])
image:
[![enter image description here][1]][1]
So, what i needed is to make the following generations replace the previous ones on the HTML display.
var gfg=new Array(10);
for (var COL=0; COL<gfg.length;COL++){
gfg[COL]=new Array(10);
}
run();
function run(){
board1();
rules();
}
function rules(){
for (var i=0; i<10;i++){
for(var j=0; j<10; j++){
const cell = gfg[i][j];
let numNeighbours = 0;
for (let x = -1; x < 2; x++) {
for (let y = -1; y < 2; y++) {
if (x === 0 && y === 0) {
continue;
}
var x_cell = i + x;
var y_cell = j + y;
if (x_cell > 0 && y_cell > 0 && x_cell <0 && y_cell <0) {
const currentNeighbour = 1;
numNeighbours=numNeighbours+currentNeighbour;
}
}
}
if (cell === 1 && numNeighbours < 2) {
gfg[i][j] = 0;
} else if (cell === 1 && numNeighbours > 3) {
gfg[i][j] = 0;
} else if (cell === 0 && numNeighbours === 3) {
gfg[i][j] = 1;
}
}
draw();
}
}
function draw(){
for (var i=0; i<10;i++){
for(var j=0; j<10; j++){
//Writes in HTML according to the coordinate value
if(gfg[i][j]===0){
document.write("◻");
}else if(gfg[i][j]===1){
document.write("◼");
}
}
document.write("<br>");
}
}
//predefined board
function board1() {
gfg[0][0] = 1;
gfg[0][1] = 0;
gfg[0][2] = 1;
gfg[0][3] = 0;
gfg[0][4] = 0;
gfg[0][5] = 1;
gfg[0][6] = 0;
gfg[0][7] = 0;
gfg[0][8] = 0;
gfg[0][9] = 1;
gfg[1][0] = 0;
gfg[1][1] = 0;
gfg[1][2] = 0;
gfg[1][3] = 0;
gfg[1][4] = 0;
gfg[1][5] = 0;
gfg[1][6] = 0;
gfg[1][7] = 1;
gfg[1][8] = 0;
gfg[1][9] = 0;
gfg[2][0] = 0;
gfg[2][1] = 0;
gfg[2][2] = 0;
gfg[2][3] = 1;
gfg[2][4] = 0;
gfg[2][5] = 1;
gfg[2][6] = 1;
gfg[2][7] = 0;
gfg[2][8] = 0;
gfg[2][9] = 0;
gfg[3][0] = 0;
gfg[3][1] = 0;
gfg[3][2] = 1;
gfg[3][3] = 0;
gfg[3][4] = 1;
gfg[3][5] = 0;
gfg[3][6] = 0;
gfg[3][7] = 0;
gfg[3][8] = 0;
gfg[3][9] = 1;
gfg[4][0] = 0;
gfg[4][1] = 0;
gfg[4][2] = 0;
gfg[4][3] = 0;
gfg[4][4] = 1;
gfg[4][5] = 0;
gfg[4][6] = 0;
gfg[4][7] = 0;
gfg[4][8] = 0;
gfg[4][9] = 0;
gfg[5][0] = 0;
gfg[5][1] = 1;
gfg[5][2] = 0;
gfg[5][3] = 0;
gfg[5][4] = 0;
gfg[5][5] = 0;
gfg[5][6] = 0;
gfg[5][7] = 0;
gfg[5][8] = 0;
gfg[5][9] = 0;
gfg[6][0] = 0;
gfg[6][1] = 0;
gfg[6][2] = 0;
gfg[6][3] = 0;
gfg[6][4] = 1;
gfg[6][5] = 0;
gfg[6][6] = 1;
gfg[6][7] = 0;
gfg[6][8] = 1;
gfg[6][9] = 0;
gfg[7][0] = 1;
gfg[7][1] = 0;
gfg[7][2] = 0;
gfg[7][3] = 1;
gfg[7][4] = 0;
gfg[7][5] = 0;
gfg[7][6] = 0;
gfg[7][7] = 1;
gfg[7][8] = 0;
gfg[7][9] = 0;
gfg[8][0] = 0;
gfg[8][1] = 0;
gfg[8][2] = 1;
gfg[8][3] = 0;
gfg[8][4] = 1;
gfg[8][5] = 0;
gfg[8][6] = 0;
gfg[8][7] = 0;
gfg[8][8] = 0;
gfg[8][9] = 0;
gfg[9][0] = 0;
gfg[9][1] = 1;
gfg[9][2] = 0;
gfg[9][3] = 0;
gfg[9][4] = 0;
gfg[9][5] = 0;
gfg[9][6] = 0;
gfg[9][7] = 0;
gfg[9][8] = 1;
gfg[9][9] = 0;
}
[1]: https://i.stack.imgur.com/ZKrFj.png
this is if you are using document.write()
All you will have to do is clear the container of the previous write with document.body.innerHTML = ""; this will clear your previous writes and then you can go through the loop again.
If you need to use html and javascript only canvas will still work as it is a built in html tag. However if you still wish to proceed with using html to display your cells then create a new div tag and give it an id e.g: id="life_container" then grab a reference to this tag when the page finishes loading and on every frame empty the div then go through your loop and fill it with your elements.
var container;
document.onload = function() {
container = document.getElementById('life_container');
}
// clear container
container.innerHtml = "";
// fill container
container.innerHtml += gfg[i][j] === 0 ? "◻" : "◼";
However I might suggest some improvements by using canvas instead of html to display your game of life. You can use P5 library, to run your loop and display it. You will need to add in extra calculation to figure out "where" to draw your cell on canvas but not much more.
I have a string that I am trying to loop through. It has nested arrays and I want to get the values from each layer. However I seem to be getting an undefined from the second layer onwards.
//String [{"username":"test","usersurname":"test","cellnumber":"test","displayname":"test","profilepicture":"test","projects":[{"projectname":"test","dateadded":"test","notes":"test","image":"test"},{"task":[{"taskname":"test","taskdescription":"test","taskimage":"test"}]}]}]
//My for loop - All variables are declared prior
for(var i = 0; i < data.length; i++){
username = data[i].username;
console.log(username);
usersurname = data[i].usersurname;
cellnumber = data[i].cellnumber;
displayname = data[i].displayname;
profilepicture = data[i].profilepicture;
for(var j = 0; j < data[i].projects.length; j++){
dateadded = data[i].projects[j].dateadded;
console.log(dateadded);
notes = data[i].projects[j].notes;
image = data[i].projects[j].image;
for(var k = 0; k < data[i].projects[j].task.length; k++){
taskname = data[i].projects[j].task[k].taskname;
console.log(taskname);
taskdescription = data[i].projects[j].task[k].taskdescription;
taskimage = data[i].projects[j].task[k].taskimage;
}
}
}
Please check undefined end errors in your code. if something is undefined loop will break.
for (var i = 0; i < data.length; i++) {
username = data[i].username;
console.log(username);
usersurname = data[i].usersurname;
cellnumber = data[i].cellnumber;
displayname = data[i].displayname;
profilepicture = data[i].profilepicture;
if("undefined" != typeof (data[i].projects))
{
for (var j = 0; j < data[i].projects.length; j++) {
dateadded = data[i].projects[j].dateadded;
console.log(dateadded);
notes = data[i].projects[j].notes;
image = data[i].projects[j].image;
if ("undefined" != typeof (data[i].projects[j].task)) {
for (var k = 0; k < data[i].projects[j].task.length; k++) {
taskname = data[i].projects[j].task[k].taskname;
console.log(taskname);
taskdescription = data[i].projects[j].task[k].taskdescription;
taskimage = data[i].projects[j].task[k].taskimage;
}
}
}
}
}
I am in the process of creating a calculator in javascript, and am trying to make a backspace. My initial thought was to use the .slice function, and it works, to a point. It works in the way that it takes a number off, but I am having trouble getting it to actually take off the number from the first value, if that makes any sense. It doesn't work on the first time, for example, if I type in 12, then use the backspace, then make the number 13 and do 13 + 6; it will come up with NaN. However if I do that same process again, it works as long as i use my clear button and not refresh the page. I have tried everything I can think of, bu't can't get it to work. Here is the code, sorry its a lot, but I figured it be better to have it all there. I am open to any suggestions, but prefer not to use jQuery, as I haven't yet learned a single thing about jQuery
Code:
//Variables
var xValue = 0;
var xValue2 = 0;
//Button Values
var plusButton = 0;
var subButton = 0;
var timesButton = 0;
var divideButton = 0;
var squaredButton = 0;
var powerButton = 0;
//Answers
var sum = 0;
var difference = 0;
var product = 0;
var quotent = 0;
var square = 0;
var power = 0;
//Functions
function add () {
if (plusButton >= 1) {
xValue2 = xValue;
xValue = "";
}
subButton = 0;
timesButton = 0;
divideButton = 0;
squaredButton = 0;
powerButton = 0;
//alert(xValue);
}
function addFunction () {
sum = +xValue + +xValue2;
answer.innerHTML = sum;
}
function subtract () {
if (subButton >= 1) {
xValue2 = xValue;
xValue = "";
}
plusButton = 0;
timesButton = 0;
divideButton = 0;
squaredButton = 0;
powerButton = 0;
}
function subtractFunction () {
difference = +xValue2 - +xValue1;
answer.innerHTML = difference;
}
function multiply () {
if(timesButton >= 1) {
temp = xValue2;
xValue2 = xValue;
xValue = "";
}
subButton = 0;
plusButton = 0;
divideButton = 0;
squaredButton = 0;
powerButton = 0;
}
function multiplyFunction () {
product = +xValue * +xValue2;
answer.innerHTML = product;
}
function divide () {
if(divideButton >= 1) {
temp = xValue2;
xValue2 = xValue;
xValue = "";
}
subButton = 0;
plusButton = 0;
timesButton = 0;
squaredButton = 0;
powerButton = 0;
}
function divideFunction () {
var quotent = +xValue / +xValue2;
answer.innerHTML = quotent;
}
function squared () {
subButton = 0;
plusButton = 0;
timesButton = 0;
divideButton = 0;
powerButton = 0;
}
function squaredFunction () {
square = Math.pow(xValue, 2);
answer.innerHTML = square;
}
function powerNum () {
if(powerButton >= 1) {
xValue2 = xValue;
xValue = "";
}
plusButton = 0;
subButton = 0;
timesButton = 0;
divideButton = 0;
squaredButton = 0;
}
function powerFunction () {
var power = Math.pow(xValue2, xValue);
answer.innerHTML = power;
}
function compute () {
if(plusButton >= 1) {
addFunction();
xValue = sum;
}
else if (subButton >= 1) {
subtractFunction();
xValue = difference;
}
else if (timesButton >= 1) {
multiplyFunction();
xValue = product;
}
else if (divideButton >= 1) {
divideFunction();
xValue = quotent;
}
else if (squaredButton >= 1) {
squaredFunction();
xValue = square;
}
else if (powerButton >= 1) {
powerFunction();
xValue2 = power;
}
xValue2 = 0;
plusButton = 0;
subButton = 0;
timesButton = 0;
divideButton = 0;
squaredButton = 0;
powerButton = 0;
}
function clearScreen() {
answer.innerHTML = "";
xValue = 0;
plusButton = 0;
xValue2 = 0;
temp = 0;
}
function backOne () {
var str = answer.innerHTML;
var res = str.slice(0, -1);
answer.innerHTML = res;
xValue = parseInt(res);
}
You can use substring on the current displayed value in the calculator and replace the current value with the substring of it. The substring would be (0, length - 1).
http://www.w3schools.com/jsref/jsref_substring.asp
EDIT: should be length - 1
So, I'm new to javascript.
My code is the following, it is based on a xaml file with a canvas and a couple of borders in it:
var defaultPage = null;
var aantalKliks;
var correcteBorders;
var incorrecteBorders;
var geenAntwBorders;
function onLoaded() {
defaultPage = document.getElementById('DefaultPage');
alert('In onloaded van Default.xaml.');
aantalKliks = 0;
aantalBorderKliks = 0;
correcteBorders = new Array();
for (var i = 0; i < 3; i++) {
correcteBorders[i] = defaultPage.content.findName('CorrecteBorder' + i);
}
incorrecteBorders = new Array();
for (var i = 0; i < 3; i++) {
incorrecteBorders[i] = defaultPage.content.findName('IncorrecteBorder' + i);
}
geenAntwBorders = new Array();
for (var i = 0; i < 3; i++) {
geenAntwBorders[i] = defaultPage.content.findName('GeenAntwBorder' + i);
}
}
function OnCanvasClicked() {
if (aantalKliks == 2) {
aantalKliks = 0;
}
if (aantalKliks == 0) {
for (var i = 0; i < correcteBorders.length; i++) {
correcteBorders[i].Visibility = 'Visible';
}
for (var i = 0; i < incorrecteBorders.length; i++) {
incorrecteBorders[i].Visibility = 'Visible';
}
for (var i = 0; i < geenAntwBorders.length; i++) {
geenAntwBorders[i].Visibility = 'Visible';
}
} else if (aantalKliks == 1) {
for (var i = 0; i < correcteBorders.length; i++) {
correcteBorders[i].Visibility = 'Collapsed';
}
for (var i = 0; i < incorrecteBorders.length; i++) {
incorrecteBorders[i].Visibility = 'Collapsed';
}
for (var i = 0; i < geenAntwBorders.length; i++) {
geenAntwBorders[i].Visibility = 'Collapsed';
}
aantalKliks++;
}
function borderClicked(sender) {
for (var i = 0; i < correcteBorders.length; i++) {
correcteBorders[i].Visibility = 'Collapsed';
}
for (var i = 0; i < incorrecteBorders.length; i++) {
incorrecteBorders[i].Visibility = 'Collapsed';
}
for (var i = 0; i < geenAntwBorders.length; i++) {
geenAntwBorders[i].Visibility = 'Collapsed';
}
sender['Visibility'] = 'Visible';
}
The function OnCanvasClicked is triggered when I click anywhere in the canvas and makes all borders disappear/reappear. The function borderClicked is triggered when I click a specific border. The function borderClicked does trigger when I click a specific border, however the OnCanvasClicked function also gets executed right after, which causes an unwanted result.I think I need some way to ignore the OnCanvasClicked function if I click on a border, I did google this but to be honest I didn't really understand what they meant in most of the solutions, so I was hoping someone could explain it to me in a simple way what I need to do (and what I'm doing).
You need to set event.stopPropagation() when borderClicked function is fire
Try this which will prevent Javascript to further execution
event.preventDefault()
#Harshit is correct
You need to set event.stopPropagation() when borderClicked function is fire
I just wanted to add this link/sample which I found very usefull to understand bubbling
http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/ie9_event_phases.htm