This is the code -
<input type="text" id="field">
<input type="button" onclick="test()">
<p id="demo"></p>
<script type="text/javascript">
function test(){
var a = document.getElementById("field").value;
var b = a.split(" ");
for(var i=0; i<b.length; i++){
var x[i] = 0;
for(var j=0; j<b[i].length; j++){
if(b[i][j] == 'e' || b[i][j] == 'a' || b[i][j] == 'i' || b[i][j] == 'o' || b[i][j] == 'n' || b[i][j] == 'r' || b[i][j] == 't' || b[i][j] == 'l' || b[i][j] == 's' || b[i][j] == 'u'){
x[i]++;
}
else if(b[i][j] == 'd' || b[i][j] == 'g'){
x[i]+=2;
}
else if(b[i][j] == 'b' || b[i][j] == 'c' || b[i][j] == 'm' || b[i][j] == 'p'){
x[i]+=3;
}
else if(b[i][j] == 'f' || b[i][j] == 'h' || b[i][j] == 'w' || b[i][j] == 'y'){
x[i]+=4;
}
else if(b[i][j] == 'k'){
x[i]+=5;
}
else if(b[i][j] == 'j' || b[i][j] == 'x'){
x[i]+=8;
}
else{
x[i]+=10;
}
}
}
document.getElementById("demo").innerHTML = x[0];
/*if(x[0] > x[1]){
document.getElementById("demo").innerHTML = b[0];
}
else{
document.getElementById("demo").innerHTML = b[1];
}*/
}
</script>
</body>
I am not getting any output for this code. I am printing here x[0] but not getting anything. Please help me with this code. What's wrong in this code. I tried everything.
Please Try This
function test(){
var a = document.getElementById("field").value;
var b = a.split(" "),x;
var x =[];
for(var i=0; i<b.length; i++){
x[i] = 0;
for(var j=0; j<b[i].length; j++){
if(b[i][j] == 'e' || b[i][j] == 'a' || b[i][j] == 'i' || b[i][j] == 'o' || b[i][j] == 'n' || b[i][j] == 'r' || b[i][j] == 't' || b[i][j] == 'l' || b[i][j] == 's' || b[i][j] == 'u'){
x[i]++;
}
else if(b[i][j] == 'd' || b[i][j] == 'g'){
x[i]+=2;
}
else if(b[i][j] == 'b' || b[i][j] == 'c' || b[i][j] == 'm' || b[i][j] == 'p'){
x[i]+=3;
}
else if(b[i][j] == 'f' || b[i][j] == 'h' || b[i][j] == 'w' || b[i][j] == 'y'){
x[i]+=4;
}
else if(b[i][j] == 'k'){
x[i]+=5;
}
else if(b[i][j] == 'j' || b[i][j] == 'x'){
x[i]+=8;
}
else{
x[i]+=10;
}
}
}
document.getElementById("demo").innerHTML = x[0];
/*if(x[0] > x[1]){
document.getElementById("demo").innerHTML = b[0];
}
else{
document.getElementById("demo").innerHTML = b[1];
}*/
}
You declared the x array inside a for loop therefore it's not available outside of it. Try moving the declaration outside of the loop.
This issue is caused by your wrong array declaration var x[i] = 0;
Change it to something like this: var x = new Array();
Then access each index via x[index]
See https://www.w3schools.com/js/js_arrays.asp
Try this:
function test(){
var a = document.getElementById("field").value;
console.log(a);
var b = a.split(" ");
console.log(b);
for(var i = 0; i < b.length; i++) {
var x = [];
x[i] = 0;
for(var j=0; j<b[i].length; j++){
if(b[i][j] == 'e' || b[i][j] == 'a' || b[i][j] == 'i' || b[i][j] == 'o' || b[i][j] == 'n' || b[i][j] == 'r' || b[i][j] == 't' || b[i][j] == 'l' || b[i][j] == 's' || b[i][j] == 'u'){
x[i]++;
}
else if(b[i][j] == 'd' || b[i][j] == 'g'){
x[i]+=2;
}
else if(b[i][j] == 'b' || b[i][j] == 'c' || b[i][j] == 'm' || b[i][j] == 'p'){
x[i]+=3;
}
else if(b[i][j] == 'f' || b[i][j] == 'h' || b[i][j] == 'w' || b[i][j] == 'y'){
x[i]+=4;
}
else if(b[i][j] == 'k'){
x[i]+=5;
}
else if(b[i][j] == 'j' || b[i][j] == 'x'){
x[i]+=8;
}
else{
x[i]+=10;
}
}
document.getElementById("demo").innerHTML = x[b.length -1];
}
}
<input type="text" id="field">
<input type="button" onclick="test()">
<p id="demo"></p>
This line itself is a problem var x[i] = 0; That's not how you declare an array. Here is how you do it var x = []; but since you want to set the first element to 0 then you can do this var x = [0]; just replace this line and your code should work.
Also to check the problem your code in the future when you encounter error, on browser press F12 key to open developer tools then see the console window/tab and it'll tell you exactly what the problem in your code.
EDIT
After reading your code again I saw that #Ankul Chaudhary 's answer is probably what you wanted to achieve since in the comment in your code you intent to compare items inside array x which in his solution he declared array x outside of the loop which it won't reset its values and keep all the calculated values inside the array which allow you to access later in the code
Related
This is my first approach to programming and I'm trying to create a TicTacToe game.At the moment, I'm doing a function that checks if a winning play is happening, but I'm sure that there are better ways to do this that my actual code. Any suggestions?
This is what I have:
let boardGame = new Array(9)
let turn = 'x';
let winner;
let squares = document.getElementsByClassName('board') // this variable it is used in other functions that I'm not transcribing it.
let whoWins = (boardGame) =>{
if(boardGame[0] == 'x' && boardGame[1] == 'x' && boardGame[2]== 'x' || boardGame[3] == 'x' && boardGame[4] == 'x' && boardGame[5]== 'x' || boardGame[6] == 'x' && boardGame[7] == 'x' && boardGame[8]== 'x' || boardGame[0] == 'x' && boardGame[4] == 'x' && boardGame[8]== 'x' || boardGame[2] == 'x' && boardGame[4] == 'x' && boardGame[6]== 'x' || boardGame[0] == 'x' && boardGame[3] == 'x' && boardGame[6]== 'x' || boardGame[1] == 'x' && boardGame[4] == 'x' && boardGame[7]== 'x' || boardGame[2] == 'x' && boardGame[5] == 'x' && boardGame[8]== 'x'){
winner = 'x'
}
else if(boardGame[0] == 'o' && boardGame[1] == 'o' && boardGame[2]== 'o' || boardGame[3] == 'o' && boardGame[4] == 'o' && boardGame[5]== 'o' || boardGame[6] == 'o' && boardGame[7] == 'o' && boardGame[8]== 'o' || boardGame[0] == 'o' && boardGame[4] == 'o' && boardGame[8]== 'o' || boardGame[2] == 'o' && boardGame[4] == 'o' && boardGame[6]== 'o' || boardGame[0] == 'o' && boardGame[3] == 'o' && boardGame[6]== 'o' || boardGame[1] == 'o' && boardGame[4] == 'o' && boardGame[7]== 'o' || boardGame[2] == 'o' && boardGame[5] == 'o' && boardGame[8]== 'o'){
winner = 'o'
}
else{}
}
I came up with this function hoping it's not too difficult to approach with.
In case I can simplify it just let me know:)
let whoWins = (boardGame) => {
const winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8]
[2, 4, 6],
];
const winner = winningConditions.find(
(condition) =>
boardGame[condition[0]] === boardGame[condition[1]] &&
boardGame[condition[1]] === boardGame[condition[2]]
);
// if the game is not finished exit
if (winner === undefined) return;
winner = boardGame[winner[0]];
};
Grazie
Trying to rewrite some code that was very repetitive into some kind of loop, and figuring out the logic is frying my brain somewhat.
The original code looked a bit like this:
if(a){
if(b == "foo1"){
if($('#foo2').val() == a || $('#foo3').val() == a || $('#foo4').val() == a || $('#foo5').val() == a || $('#foo6').val() == a){
//do something here
}
}
}
if(a){
if(b == "foo2"){
if($('#foo1').val() == a || $('#foo3').val() == a || $('#foo4').val() == a || $('#foo5').val() == a || $('#foo6').val() == a){
//do something here
}
}
}
if(a){
if(b == "foo3"){
if($('#foo1').val() == a || $('#foo2').val() == a || $('#foo4').val() == a || $('#foo5').val() == a || $('#foo6').val() == a){
//do something here
}
}
}
if(a){
if(b == "foo4"){
if($('#foo1').val() == a || $('#foo2').val() == a || $('#foo3').val() == a || $('#foo5').val() == a || $('#foo6').val() == a){
//do something here
}
}
}
if(b == "foo5"){
if($('#foo1').val() == a || $('#foo2').val() == a || $('#foo3').val() == a || $('#foo4').val() == a || $('#foo6').val() == a){
//do something here
}
}
}
if(b == "foo6"){
if($('#foo1').val() == a || $('#foo2').val() == a || $('#foo3').val() == a || $('#foo4').val() == a || $('#foo5').val() == a){
//do something here
}
}
}
I want to rewrite this into a loop (or loops), but am struggling to get the logic right.
So far, I have this:
if (a){
for (i=0; i < 6; i++){
var fieldNames =[ "foo1", "foo2", "foo3", "foo4", "foo5", "foo6"]
console.log("i loop "+ fieldNames[i]);
if(b == fieldNames[i]){
for (j = 1; j < fieldNames.length; j++){
if($('#'+fieldNames[j]).val() == a){
//do something here
}
}
}
}
}
I know this isn't right, but can anyone help me with what the logic should be?
Thanks
Edit:
Should clarify what the variables refer to.
This function is called inline from a element on the onblur event with the line doCheck(this.value, 'foo1') (this example relates to just the first instance of that, the b input is foo2 for the second and foo3 for the third and so on...
The full function looks like this:
function doCheck(a,b)
if (a){
for (i=0; i < 6; i++){
var fieldNames =[ "foo1", "foo2", "foo3", "foo4", "foo5", "foo6"]
console.log("i loop "+ fieldNames[i]);
if(b == fieldNames[i]){
for (j = 1; j < fieldNames.length; j++){
if($('#'+fieldNames[j]).val() == a){
//do something here
}
}
}
}
}
}
So the variable a is the value of whatever is in the select element and the b variable is the field name.
You could produce a list of possible fields, remove b from that list, then compare against the remaining ones.
if (a) {
var fieldNames = ['foo1', 'foo2', 'foo3', 'foo4', 'foo5', 'foo6'];
// Remove b from the fields
fieldNames.splice(fieldNames.indexOf(b), 1);
var doSomething = fieldNames.reduce(function(prev, fieldName) {
return prev && $('#' + fieldName).val() === a;
}, true);
if (doSomething) {
// do something
}
}
Another way of looking at this would be something like this:
if (a) {
var fieldNames = ['foo1', 'foo2', 'foo3', 'foo4', 'foo5', 'foo6'];
// Remove b from the fields
fieldNames.splice(fieldNames.indexOf(b), 1);
var doSomething = true;
for (var i = 0; i < fieldNames.length; i++) {
if ($('#' + fieldNames[i]).val() !== a) {
doSomething = false;
break;
}
}
if (doSomething) {
// do something
}
}
I assume that your problem shall be here :
if($('#fieldNames[j]').val() == a){
Repalce with :
if($('#' + fieldNames[j]).val() == a){
Moreover, your loop may be updated like that,
var fieldNames =[ "foo1", "foo2", "foo3", "foo4", "foo5", "foo6"];
// Define fieldNames before the first loop
if (a){
for (i=0; i < fieldNames.length; i++){
console.log("i loop "+ fieldNames[i]);
if(b == fieldNames[i]){
for (j = 1; j < fieldNames.length; j++){ // WHY YOU START AT j=1 ? I shall start at j=0 in my opinion
if($('#fieldNames[j]').val() == a){
//do something here
break; // <=== EXIT 2nd LOOP IF YOU FIND SOMETHING
}
}
}
break; // <=== EXIT 1st LOOP IF YOU FIND SOMETHING
}
}
I am not sure you want the //do something here to be the same for all if blocks in the original code. If you want the same then you can make the loop as you suggest, otherwise not.
Why not put the values i.e. $('#foo2').val() into an array and test for a and b using the indexOf() function on the array?
var fieldValues =[ $("#foo1").val(), $("#foo2").val(), etc];
if(fieldValues.indexOf(a)!=-1 || fieldValues.indexOf(b)!=-1){
//do something here
}
i'm making the tic tac toe game and im trying to fix a bug that i have now.
When i play the game and i click on the O's it changes to X how can i fix this?
I thought it would be something like: If (turn == 0 && ('td') == "") {
But that doesn't work
var newGame = function () {
$('td').one('click', function (event) {
if (turn == 0) {
$(this).text(human);
boardCheck();
checkWin();
turn == 1;
compMove();
boardCheck();
checkWin();
}
});
};
// VARIABLES
var human = 'x'; // turn = 0
var computer = 'o'; // turn = 1
var compMove;
var turn = 0; // toggles btw 0 and 1 for switching turns
var boardCheck; // function to check value in each cell
var a1; // value within each cell
var a2;
var a3;
var b1;
var b2;
var b3;
var c1;
var c2;
var c3;
var checkWin; // function that checks the board for winning combo
var xWin = false; // true if X wins
var oWin = false; // true if O wins
var winAlert; // function that declares winner and restarts game
var newGame;
var clearBoard;
// PLACES AN X OR O IN THE BOX WHEN CLICKED. TOGGLES.
var newGame = function () {
$('td').one('click', function (event) {
if (turn == 0) {
$(this).text(human);
boardCheck();
checkWin();
turn == 1;
compMove();
boardCheck();
checkWin();
}
});
};
// INITIALIZES GAME - keep after var newGame
$(document).ready(function () {
newGame();
});
// COMP MOVE AI DETECTS IF THERE ARE TWO IN A ROW NEXT TO AN EMPTY CELL AND PLACES MOVE THERE
var compMove = function () {
if (a1 == "" && ((a3 == "x" && a2 == "x") || (c3 == "x" && b2 == "x") || (c1 == "x" && b1 == "x"))) {
$('#a1').text("o");
turn = 0;
} else {
if (a2 == "" && ((a1 == "x" && a3 == "x") || (c2 == "x" && b2 == "x"))) {
$('#a2').text("o");
turn = 0;
}
else{
if (a3 == "" && ((a1 == "x" && a2 == "x") || (c1 == "x" && b2 == "x") || (c3 == "x" && b3 == "x"))) {
$('#a3').text("o");
turn = 0;
}
else{
if (c3 == "" && ((c1 == "x" && c2 == "x") || (a1 == "x" && b2 == "x") || (a3 == "x" && b3 == "x"))) {
$('#c3').text("o");
turn = 0;
}
else{
if (c1 == "" && ((c3 == "x" && c2 == "x") || (a3 == "x" && b2 == "x") || (a1 == "x" && b1 == "x"))) {
$('#c1').text("o");
turn = 0;
}
else{
if (c2 == "" && ((c3 == "x" && c1 == "x") || (a2 == "x" && b2 == "x"))) {
$('#c2').text("o");
turn = 0;
}
else{
if (b1 == "" && ((b3 == "x" && b2 == "x") || (a1 == "x" && c1 == "x"))) {
$('#b1').text("o");
turn = 0;
}
else{
if (b3 == "" && ((a3 == "x" && c3 == "x") || (b2 == "x" && b1 == "x"))) {
$('#b3').text("o");
turn = 0;
}
else{
if (b2 == "" && ((a3 == "x" && c1 == "x") || (c3 == "x" && a1 == "x") || (b3 == "x" && b1 == "x") || (c2 == "x" && a2 == "x"))) {
$('#b2').text("o");
turn = 0;
}
else{ // IF NO OPP TO BLOCK A WIN, THEN PLAY IN ONE OF THESE SQUARES
if (b2 == "") {
$('#b2').text("o");
turn = 0;
}
else{
if (a1 == "") {
$('#a1').text("o");
turn = 0;
}
else{
if (c3 == "") {
$('#c3').text("o");
turn = 0;
}
else {
if (c2 == "") {
$('#c2').text("o");
turn = 0;
}
else{
if (b1 == "") {
$('#b1').text("o");
turn = 0;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
};
// CREATES A FUNCTION TO DETECT WHAT IS IN EACH BOX AFTER EACH MOVE
boardCheck = function () {
a1 = $('#a1').html();
a2 = $('#a2').html();
a3 = $('#a3').html();
b1 = $('#b1').html();
b2 = $('#b2').html();
b3 = $('#b3').html();
c1 = $('#c1').html();
c2 = $('#c2').html();
c3 = $('#c3').html();
};
// CREATES A FUNCTION TO DETECT A WIN OR A TIE
checkWin = function () { // CHECKS IF X WON
if ((a1 == a2 && a1 == a3 && (a1 == "x")) || //first row
(b1 == b2 && b1 == b3 && (b1 == "x")) || //second row
(c1 == c2 && c1 == c3 && (c1 == "x")) || //third row
(a1 == b1 && a1 == c1 && (a1 == "x")) || //first column
(a2 == b2 && a2 == c2 && (a2 == "x")) || //second column
(a3 == b3 && a3 == c3 && (a3 == "x")) || //third column
(a1 == b2 && a1 == c3 && (a1 == "x")) || //diagonal 1
(a3 == b2 && a3 == c1 && (a3 == "x")) //diagonal 2
) {
xWin = true;
winAlert();
} else { // CHECKS IF O WON
if ((a1 == a2 && a1 == a3 && (a1 == "o")) || //first row
(b1 == b2 && b1 == b3 && (b1 == "o")) || //second row
(c1 == c2 && c1 == c3 && (c1 == "o")) || //third row
(a1 == b1 && a1 == c1 && (a1 == "o")) || //first column
(a2 == b2 && a2 == c2 && (a2 == "o")) || //second column
(a3 == b3 && a3 == c3 && (a3 == "o")) || //third column
(a1 == b2 && a1 == c3 && (a1 == "o")) || //diagonal 1
(a3 == b2 && a3 == c1 && (a3 == "o")) //diagonal 2
) {
oWin = true;
winAlert();
} else { // CHECKS FOR TIE GAME IF ALL CELLS ARE FILLED
if (((a1 == "x") || (a1 == "o")) && ((b1 == "x") || (b1 == "o")) && ((c1 == "x") || (c1 == "o")) && ((a2 == "x") || (a2 == "o")) && ((b2 == "x") || (b2 == "o")) && ((c2 == "x") || (c2 == "o")) && ((a3 == "x") || (a3 == "o")) && ((b3 == "x") || (b3 == "o")) && ((c3 == "x") || (c3 == "o"))) {
alert("It's a tie!");
clearBoard();
}
}
}
};
// DECLARES WHO WON
var winAlert = function () {
if (xWin == true) {
alert("You won!");
clearBoard(); // THIS DOESN'T WORK
} else {
if (oWin == true) {
alert("Sorry, you lose!");
clearBoard(); // THIS DOESN'T WORK
}
}
};
// NEWGAME BUTTON CLEARS THE BOARD, RESTARTS GAME, AND RESETS THE WINS
var clearBoard = $('#restart').click(function (event) {
a1 = $('#a1').text("");
b1 = $('#b1').text("");
c1 = $('#c1').text("");
a2 = $('#a2').text("");
b2 = $('#b2').text("");
c2 = $('#c2').text("");
a3 = $('#a3').text("");
b3 = $('#b3').text("");
c3 = $('#c3').text("");
xWin = false;
oWin = false;
newGame();
window.location.reload(true); // WITHOUT THIS, THERE'S A BUG WHICH PLACES MULTIPLE 0'S ON ALL GAMES AFTER THE FIRST
});
// STILL NEED TO FIX:
// * Alert for tie game or xWin appears twice
// * X's can replace O's
// * Missed opportunities for O to win
// * Almost never let's human win
// * Clean up logic for compMove'
if (turn == 0 && $(this).text() == "") {
This is a shortened version of a conditional I've written to parse information from a vehicle VIN number. If I pass in a VIN such as JA3XXXXXXXXXXXXXX it returns and object with properties of region:'Asia';, country:'Japan'; and make:'Isuzu'; but if I pass it 2A5XXXXXXXXXXXXXX I would expect an object with properties set to region:'North America'; , country:'Canada'; and make:'Chrysler'; instead I get an object with the region property set to 'Asia' and that is it. Here is a jsFiddle with the code shown below.
var vehicle = {},
nthDigit = function (stringifiedVin, i) {
var nthChar = stringifiedVin.charAt(i);
return nthChar;
},
parseVin = function () {
var i = 0;
for (i = 0; i < 16; i += 1) {
if (i === 0) {
if (nthDigit(stringifiedVin, 0) === 'J' || 'K' || 'L' || 'M' || 'N' || 'P' || 'R') {
vehicle.region = 'Asia';
switch (nthDigit(stringifiedVin, i)) {
case 'J':
vehicle.country = 'Japan';
switch (nthDigit(stringifiedVin, 1)) {
case 'A':
if (nthDigit(stringifiedVin, 2) === 'A' || 'B' || 'C' || 'D' || 'E' || 'F' || 'G' || 'H' || 'J' || 'K' || 'L' || 'M' || 'N' || 'P' || 'R' || 'S' || 'T' || 'U' || 'V' || 'W' || 'X' || 'Y' || 'Z') {
vehicle.make = 'Isuzu';
} else if (nthDigit(stringifiedVin, 2) === '3' || '4' || '5' || '6' || '7') {
vehicle.make = 'Mitsubishi';
} else {
vehicle.make = 'Not Read';
}
break;
}
break;
}
} else if (nthDigit(stringifiedVin, 0) === '1' || '2' || '3' || '4' || '5') {
vehicle.region = 'North America';
if (nthDigit(stringifiedVin, 0) === '2') {
vehicle.country = "Canada";
switch (nthDigit(stringifiedVin, 1)) {
case 'A':
if (nthDigit(stringifiedVin, 2) === '2' || '3' || '4' || '5' || '6' || '7' || '8') {
vehicle.make = 'Chrysler';
} else {
vehicle.make = 'Not Read';
}
break;
}
break;
}
}
return vehicle;
}
}
}
I don't thing the || parts work the way you think they do. This will run the Alert() since '2' is not false:
if ('A' === '1' || '2')
alert('match')
I would use a switch or you will have to spell it out like:
var nd = nthDigit(stringifiedVin, 0);
if (nd === 'J' || nd === 'K' || nd === 'L' || ...
A shorter one:
if("JKLMNP".indexOf(nthDigit(stringifiedVin, 0)) > -1){
//....
}
#JBrooks I think you are right about how the double pipe or operator was causing trouble in the conditional statement. I think it is due to the way the operator handles falsy values as shown in this SO post. I ended up getting rid of the if statements entirely when I realized the JA3XXXXXXXXXXXXXX should have been returning Mitsubishi and not Isuzu. I found the solution here using #KennyTM answer on setting up multiple cases.
I want to convert a string to integer. I know that there are built-in functions to do it, but still i want to know why is this function not working:
JS: - saved as js1.js
function atoi(str)
{
l = str.length;
s2 = "0"
for(i=0;i<l;i++)
{
if(str.charAt(i) != '1' || str.charAt(i) != '2' || str.charAt(i) != '3' || str.charAt(i) != '4' || str.charAt(i) != '5' || str.charAt(i) != '6' || str.charAt(i) != '7' || str.charAt(i) != '8' || str.charAt(i) != '9' || str.charAt(i) != '0')
{
break;
}
s2 = s2.concat(str.charAt(i));
}
return Number(s2);
}
HTML:
<html>
<head>
<script src="js1.js">
</script>
<Script>
function printnum()
{
n = atoi(document.getElementById('numtxt').value)
document.write(n);
}
</script>
<title>
Test JS1 functions
</title>
</head>
<body>
<input type="text" id="numtxt">
<input type="button" onclick="printnum()">
</body>
</html>
Thank You.
You give up and break if the first character is not a 1 or if it is not a 2, etc.
If it is 1 then it isn't 2 and you break.
You want to be using && not ||.
this or-thing you have there is always true, like:
If a!=3||a!=4
any value a can have, this is always true, so is with more terms
You shoud use && instead of ||
if(str.charAt(i) != '1' && str.charAt(i) != '2' &&
str.charAt(i) != '3' && str.charAt(i) != '4' &&
str.charAt(i) != '5' && str.charAt(i) != '6' &&
str.charAt(i) != '7' && str.charAt(i) != '8' &&
str.charAt(i) != '9' && str.charAt(i) != '0')