I am doing some conditional concatenations on pairs of strings. if the condition is not satisfied, then a space should be added between the two
The following is a small subset of my larger code but replicates my problem
a = "ai";
b = "b";
res = "";
if (a.match(/ai$/))
{
if (b.match(/^ā/) || b.match(/^a/) ||
b.match(/^i/) || b.match(/^ī/) ||
b.match(/^u/) || b.match(/^ū/) ||
b.match(/^e/) || b.match(/^o/) ||
b.match(/^ṛ/))
{
res = a.slice(0, -1) + 'a ' + b
}
}
else
res = a+ ' ' + b
the result should be ai b
But I get ''
What am I doing wrong?
Move your else inside the first if so that that else is triggered when the inner if is not satisfied:
a = "ai";
b = "b";
res = "";
if (a.match(/ai$/))
{
if (b.match(/^ā/) || b.match(/^a/) ||
b.match(/^i/) || b.match(/^ī/) ||
b.match(/^u/) || b.match(/^ū/) ||
b.match(/^e/) || b.match(/^o/) ||
b.match(/^ṛ/))
{
res = a.slice(0, -1) + 'a ' + b
}
else{
res = a+ ' ' + b
}
}
console.log(res);
The nested if doesn't go to the outer else for example:
if (1 === 1) {
if (1 === 2) {
console.log(1);
}
}
else {
console.log(2);
}
the else statement in this case will never trigger.
It seems to me that what you need to do is simply combine the if statements:
a = "ai";
b = "b";
res = "";
if (a.match(/ai$/) && (b.match(/^ā/) || b.match(/^a/) ||
b.match(/^i/) || b.match(/^ī/) ||
b.match(/^u/) || b.match(/^ū/) ||
b.match(/^e/) || b.match(/^o/) ||
b.match(/^ṛ/))) {
res = a.slice(0, -1) + 'a ' + b;
}
else {
res = a + ' ' + b;
}
note the extra "(" after the && this is so the entire statement is treated as one unit and not seperated.
Related
I am solving an algorithm question whereby it requires me to ensure that brackets, parenthesis and braces are put in the correct order or sequence.
Here is a link to the question, https://leetcode.com/problems/valid-parentheses/
An example is shown below:
Here is my code for the solution:
const isParenthesisValid = (params) => {
myList = []
lastElement = myList[myList.length - 1]
for (let i = 0; i < params.length; i++) {
if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) {
myList.push(params[i])
} else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) {
myList.pop()
} else return false
}
return myList.length ? false : true
}
// I get false as an answer everytime whether the pattern is correct or wrong
// false
console.log(isParenthesisValid("[()]"))
But I don't know why I get false everytime, I have compared my answer with someones else answer who did the same thing but it seems I am omitting something not so obvious.
I hope someone can point out in my code where i am getting it wrong.
Your lastElement retrieves the last element of the list at the start of the program - when there is no such element - so it's always undefined. You need to retrieve the value inside the loop instead.
const isParenthesisValid = (params) => {
myList = []
for (let i = 0; i < params.length; i++) {
const lastElement = myList[myList.length - 1]
if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) {
myList.push(params[i])
} else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) {
myList.pop()
} else return false
}
return myList.length ? false : true
}
console.log(isParenthesisValid("[()]"))
Or, a bit more readably:
const isParenthesisValid = (input) => {
const openDelimiters = [];
for (const delim of input) {
const lastElement = openDelimiters[openDelimiters.length - 1];
if (delim === "(" || delim === "[" || delim === "{") {
openDelimiters.push(delim)
} else if ((delim === ")" && lastElement === "(") || (delim === "]" && lastElement === "[") || (delim === "}" && lastElement === "{")) {
openDelimiters.pop()
} else return false
}
return openDelimiters.length === 0;
}
console.log(isParenthesisValid("[()]"))
Another approach, linking each delimiter with an object:
const delims = {
')': '(',
'}': '{',
']': '[',
};
const isParenthesisValid = (input) => {
const openDelimiters = [];
for (const delim of input) {
if ('([{'.includes(delim)) {
openDelimiters.push(delim)
} else if (')]}'.includes(delim) && openDelimiters[openDelimiters.length - 1] === delims[delim]) {
openDelimiters.pop()
} else return false
}
return openDelimiters.length === 0;
}
console.log(isParenthesisValid("[()]"))
i am trying to build a calculator but in that i am unable to perform sum operation besides it concatenation is occurred how i can do this sum, also how to empty the text box when entering new value in the text-box after pressing '=' my code is this
<title>Calculator</title>
<script>
var v = 0 ;
var operator = '';
function calc(obj){
if (obj.value == '+' || obj.value == '-' || obj.value == '*' || obj.value == '/' ){
v = document.getElementById("text_field").value;
operator = obj.value;
document.getElementById("text_field").value = '';
}
else if (obj.value == '='){
if (operator == '+')
{
document.getElementById("text_field"). value = v + document.getElementById("text_field").value ;
}
if (operator == '-')
{
document.getElementById("text_field").value = v - document.getElementById("text_field").value ;
}
if (operator == '*')
{
document.getElementById("text_field").value =v * document.getElementById("text_field").value ;
}
if (operator == '/')
{
document.getElementById("text_field").value = v / document.getElementById("text_field").value ;
}
}
else {
document.getElementById("text_field").value = document.getElementById("text_field").value + obj.value;
}
}
</script>
Use parseInt: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
for example:
parseInt(document.getElementById("text_field").value)
I am making a game of tic-tac toe in javascript. I have laid out some of what I believe to be the basic building blocks:
var board = [
0, 0, 0,
0, 0, 0,
0, 0, 0
];
gameOn = true;
player1Move = true;
counter = 0;
player1 = [];
player2 = [];
var ask = console.log(prompt('where would you like to go?'));
var drawBoard = function(){
console.log(" A " + (board[0]) + "| B " + (board[1]) + "| C " + (board[2]));
console.log(" ------------- ");
console.log(" D " + (board[3]) + "| E " + (board[4]) + "| F " + (board[5]));
console.log(" ------------- ");
console.log(" G " + (board[6]) + "| H " + (board[7]) + "| I " + (board[8]));
console.log(" ------------- ");
};
var solutions = [
(board[0] && board[1] && board[2]) || (board[3] && board[4] && board[5]) ||
(board[6] && board[7] && board[8]) || (board[0] && board[3] && board[6]) ||
(board[1] && board[4] && board[7]) || (board[2] && board[5] && board[8]) ||
(board[0] && board[4] && board[8]) || (board[2] && board[4] && board[6])
];
while (gameOn === true){
// for loop for game logic
for (var i = 0 ; i < 9; i++){
if (player1Move === true) {
player1.push(ask);
drawBoard();
player1Move = false;
} else if (player1Move === false){
player2.push(ask);
drawBoard();
player1Move = true;
} else if ((player1 || player2) === solutions){
gameOn = false;
console.log((player1 || player2) + "wins!");
} else {
gameOn = false;
console.log("Tie Game!");
}
}
}
I know that the syntax of my main loop is incorrect. Why can't I do what is currently written? If you had this existing code, what type of loop setup would you use to accomplish this? Sorry if this seems not specific enough, I am just lost in the logic of it all!
With this existing loop all I am trying to do is go through and prompt the 2 users 9 times(because maximum moves = 9) in total for now. Once that works than I will keep adding more game logic into it. Why can't I get the prompt to come up 9 times? The current result is that it prompts me once, prints out the board 9 times and false after all of it.
This just needs to work in a terminal window for now too by the way.
I changed your code as little as possible, but a few things are different, which I am explaining bit by bit.
var board = {
A: null,
B: null,
C: null,
D: null,
E: null,
F: null,
G: null,
H: null,
I: null
};
gameOn = true;
player1Move = true;
var drawBoard = function(){
console.log(" A " + (board.A || '') + "| B " + (board.B || '') + "| C " + (board.C || ''));
console.log(" ------------- ");
console.log(" D " + (board.D || '') + "| E " + (board.E || '') + "| F " + (board.F || ''));
console.log(" ------------- ");
console.log(" G " + (board.G || '') + "| H " + (board.H || '') + "| I " + (board.I || ''));
console.log(" ------------- ");
};
var solutions = function() {
return (board.A && (board.A == board.B && board.A == board.C))
|| (board.D && (board.D == board.E && board.D == board.F))
|| (board.G && (board.G == board.H && board.G == board.I));
};
drawBoard();
var currentPlayer;
while (gameOn === true){
// for loop for game logic
for (var i = 0 ; i < 9; i++){
if (solutions()){
console.log(currentPlayer + " wins!");
gameOn = false;
break;
}
//else {
// gameOn = false;
// console.log("Tie Game!");
//}
currentPlayer = 'Player 1';
if(!player1Move)
currentPlayer = 'Player 2';
var ask = prompt(currentPlayer + ': where would you like to go (A or B or C or ..)?');
if(ask == 'exit') {
gameOn = false;
break;
}
if (player1Move === true) {
//player1.push(ask);
board[ask] = 'X';
drawBoard();
player1Move = false;
} else if (player1Move === false){
board[ask] = 'O';
drawBoard();
player1Move = true;
}
}
}
It's not completely finished, but then that's something you can do afterwards, and probably you didn't want me to do it all for you.
This all works in a Chrome console.
There were a couple of basic things that were holding you back:
var ask = console.log(prompt('where would you like to go?')); should be var ask = prompt(currentPlayer + ': where would you like to go?'); - your version was filling ask with null.
This prompt was also in the wrong place: it needs to be in the loop, and after drawBoard(), so that the player has something to look at.
I've changed the board from an array into an object, so that player answers like 'A' refer directly to the object fields. And that way the player arrays could be removed.
The solutions() function needs completing, as you can see, and there may be a neater way of doing this.
I added the possibility of writing 'exit' in the prompt, otherwise there's no way of exiting the game early.
I didn't finish the 'Tie game!' code.
Make sure you understand the global object is, and what window.prompt is, and what console.log is in your context. It is absolutely necessary to get to know a debugger for your environment. In Chrome it's called Developer Tools.
window.prompt is not very useful in code sandboxes like jsfiddle, or the Stack overflow bulit-in ones. I suggest using HTML for your user interface.
function init() {
trapForm();
trapInput();
toggleCurrentUser();
askUser();
}
var game = [
[null,null,null],
[null,null,null],
[null,null,null]
];
var trapInput = function() {
// capture input and use to to create a play in the game
document.querySelector('#go').addEventListener('click',function(ev) {
var position = document.querySelector('#square').valueAsNumber;
if (position < 10 && position > 0) {
// render X or O to the HTML
var td = document.querySelectorAll('#t3 td')[position-1];
td.innerHTML = currentUser;
// modify the corresponding game array
var row = Math.floor( (position-1) / 3 );
var col = ( (position+2) % 3) ;
game[row][col] = currentUser;
// this helps us visualize what's happening
debug(game);
checkGameStatus();
toggleCurrentUser();
} else {
debug({"msg":"illegal move"});
}
});
};
var trapForm = function() {
// prevent form from submitting
var f = document.querySelector('#f');
f.addEventListener('submit',function(ev) {
ev.preventDefault();
trapInput();
});
};
;(function(window,document,undefined){
"use strict";
function init() {
trapForm();
trapInput();
toggleCurrentUser();
askUser();
}
var currentUser = 'Y';
var toggleCurrentUser = function(){
if (currentUser === 'X') {
currentUser = 'Y';
} else {
currentUser = 'X';
}
document.querySelector('#currentuser').value = currentUser;
};
var isVirginal = function(game) {
return game.every(function(row) {
return row.every(function(cell) { return (cell === null); });
});
};
var isStaleMate = function(game){
return game.every(function(row){
return row.every(function(cell){
return (cell === 'X' || cell === 'Y');
});
});
};
var horizontalWinner = function(game) {
var r = false;
return game.some(function(row){
var firstletter = row[0];
if (firstletter === null) {
return false;
} else {
return row.every(function(cell){
return ( cell !== null && cell === firstletter);
});
}
});
};
var verticalWinner = function(game) {
var r = false;
for (var i = 0; i < 4; i++) {
if (game[0][i] === null) {
continue;
}
if (game[0][i] === game[1][i] && game[1][i] === game[2][i]) {
r = game[0][i];
break;
}
};
return r;
};
var diagonalWinner = function(game) {
var r = false;
if (game[0][0] !== null && (game[0][0] === game[1][1] === game[2][2])) {
r = game[0][0];
}
if (game[0][2] !== null && (game[0][2] === game[1][1] === game[2][0])) {
r = game[0][2];
}
return r;
};
var checkGameStatus = function(){
var r = 'unknown';
if (isVirginal(game)) {
r = 'Virginal Game';
} else {
r = 'In Play';
}
if (isStaleMate(game)) {
r = 'Stale Mate';
}
if (diagonalWinner(game)){
r = 'Diagonal Winner: ' + diagonalWinner(game);
}
if (verticalWinner(game)) {
r = 'vertical Winner: ' + verticalWinner(game);
}
if (horizontalWinner(game)) {
r = 'Horizontal Winner: ' + horizontalWinner(game);
}
document.querySelector('#status').value = r;
};
var debug = function(stuff) {
document.querySelector('#debug').innerHTML = JSON.stringify(stuff);
};
var game = [
[null,null,null],
[null,null,null],
[null,null,null]
];
var trapInput = function() {
// capture input and use to to create a play in the game
document.querySelector('#go').addEventListener('click',function(ev) {
var position = document.querySelector('#square').valueAsNumber;
if (position < 10 && position > 0) {
// render X or O to the HTML
var td = document.querySelectorAll('#t3 td')[position-1];
td.innerHTML = currentUser;
// modify the corresponding game array
var row = Math.floor( (position-1) / 3 );
var col = ( (position+2) % 3) ;
game[row][col] = currentUser;
// this helps us visualize what's happening
debug(game);
checkGameStatus();
toggleCurrentUser();
} else {
debug({"msg":"illegal move"});
}
});
};
var trapForm = function() {
// prevent form from submitting
var f = document.querySelector('#f');
f.addEventListener('submit',function(ev) {
ev.preventDefault();
trapInput();
});
};
document.addEventListener('DOMContentLoaded',init);
})(window,document);
#t3 {
font-family: "Courier New";
font-size: xx-large;
}
#t3 td {
border: 1px solid silver;
width: 1em;
height: 1em;
vertical-align: middle;
text-align: center;
}
#f {
position: relative;
}
#f label, input, button {
float: left;
width: 200px;
}
#f label, button {
clear: left;
}
hr {
clear: both;
visibility: hidden;
}
<form id="f">
<label for="currentuser">Current User</label>
<input type="text" readonly id="currentuser" name="currentuser" />
<label for="square">What Square (1-9)?</label>
<input type="number" step="1" min="1" max="9" id="square" name="square" />
<label for="status">Game Status</label>
<input type="text" readonly id="status" name="status" value="Virgin Game" />
<button type="button" id="go">make move</button>
</form>
<hr />
<table id="t3">
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<pre id="debug"></pre>
I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I'm making a poker game and what I'm trying to do is determine whether i have a pair, two pairs, three of a kind, four of a kind or a full house.
For instance, in [1, 2, 3, 4, 4, 4, 3], 1 appears one time, 4 appears three times, and so on.
How could I possibly ask my computer to tell me how many times an array element appears?
Solved, here's the final product.
<script type="text/javascript">
var deck = [];
var cards = [];
var convertedcards = [];
var kinds = [];
var phase = 1;
var displaycard = [];
var options = 0;
var endgame = false;
// Fill Deck //
for(i = 0; i < 52; i++){
deck[deck.length] = i;
}
// Distribute Cards //
for(i = 0; i < 7; i++){
cards[cards.length] = Number(Math.floor(Math.random() * 52));
if(deck.indexOf(cards[cards.length - 1]) === -1){
cards.splice(cards.length - 1, cards.length);
i = i - 1;
}else{
deck[cards[cards.length - 1]] = "|";
}
}
// Convert Cards //
for(i = 0; i < 7; i++){
convertedcards[i] = (cards[i] % 13) + 1;
}
// Cards Kind //
for(i = 0; i < 7; i++){
if(cards[i] < 13){
kinds[kinds.length] = "H";
}else if(cards[i] < 27 && cards[i] > 12){
kinds[kinds.length] = "C";
}else if(cards[i] < 40 && cards[i] > 26){
kinds[kinds.length] = "D";
}else{
kinds[kinds.length] = "S";
}
}
// Card Display //
for(i = 0; i < 7; i++){
displaycard[i] = convertedcards[i] + kinds[i];
}
// Hand Strenght //
var handstrenght = function(){
var usedcards = [];
var count = 0;
var pairs = [];
for(i = 0, a = 1; i < 7; a++){
if(convertedcards[i] === convertedcards[a] && a < 7 && usedcards[i] != "|"){
pairs[pairs.length] = convertedcards[i];
usedcards[a] = "|";
}else if(a > 6){
i = i + 1;
a = i;
}
}
// Flush >.< //
var flush = false;
for(i = 0, a = 1; i < 7; i++, a++){
if(kinds[i] === kinds[a] && kinds[i] != undefined){
count++;
if(a >= 6 && count >= 5){
flush = true;
count = 0;
}else if(a >= 6 && count < 5){
count = 0;
}
}
}
// Straight >.< //
var straight = false;
convertedcards = convertedcards.sort(function(a,b){return a-b});
if(convertedcards[2] > 10 && convertedcards[3] > 10 && convertedcards[4] > 10){
convertedcards[0] = 14;
convertedcards = convertedcards.sort(function(a,b){return a-b});
}
alert(convertedcards);
if(convertedcards[0] + 1 === convertedcards[1] && convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4]){
straight = true;
}else if(convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5]){
straight = true;
}else if(convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5] && convertedcards[5] + 1 === convertedcards[6]){
straight = true;
}
// Royal Flush, Straight Flush, Flush, Straight >.< //
var royalflush = false;
if(straight === true && flush === true && convertedcards[6] === 14){
royalflush = true;
alert("You have a Royal Flush");
}
else if(straight === true && flush === true && royalflush === false){
alert("You have a straight flush");
}else if(straight === true && flush === false){
alert("You have a straight");
}else if(straight === false && flush === true){
alert("You have a flush");
}
// Full House >.< //
if(pairs[0] === pairs[1] && pairs[1] != pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] === pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] != pairs[2] && pairs[2] === pairs[3] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}
// Four of a kind >.< //
else if(pairs[0] === pairs[1] && pairs[1] === pairs[2] && pairs.length > 0){
alert("You have four of a kind");
}
// Three of a kind >.< //
else if(pairs[0] === pairs[1] && flush === false && straight === false && pairs.length === 2){
alert("You have three of a kind");
}
// Double Pair >.< //
else if(pairs[0] != pairs[1] && flush === false && straight === false && pairs.length > 1){
alert("You have a double pair");
}
// Pair >.< //
else if(pairs.length === 1 && flush === false && straight === false && pairs.length === 1 ){
alert("You have a pair");
}
alert(pairs);
};
while(endgame === false){
if(phase === 1){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 2){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 3){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 4){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + " " + displaycard[6] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}
switch(options){
case 1:
if(phase === 5){
handstrenght();
endgame = true;
}else{
phase++;
}
break;
case 2:
endgame = true;
break;
default:
endgame = true;
break;
}
}
</script>
Keep a variable for the total count
Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
After the loop, total count contains the number of times the number you were looking for is in the array
Show your code and we can help you figure out where it went wrong
Here's a simple implementation (since you don't have the code that didn't work)
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
countInArray could also have been implemented as
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
More elegant, but maybe not as performant since it has to create a new array.
With filter and length it seems simple but there is a big waste of memory.
If you want to use nice array methods, the appropriate one is reduce:
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1,2,3,4,4,4,3], 4)); // 3
Well..
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
// a == {2: 5, 4: 1, 5: 3, 9: 1}
from here:
Counting the occurrences of JavaScript array elements
Or you can find other solutions there, too..
When targeting recent enough browsers, you can use filter(). (The MDN page also provides a polyfill for the function.)
var items = [1, 2, 3, 4, 4, 4, 3];
var fours = items.filter(function(it) {return it === 4;});
var result = fours.length;
You can even abstract over the filtering function as this:
// Creates a new function that returns true if the parameter passed to it is
// equal to `x`
function equal_func(x) {
return function(it) {
return it === x;
}
}
//...
var result = items.filter(equal_func(4)).length;
Here's an implementation of Juan's answer:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; ) {
if ( list[ l ] === x ) {
c++;
}
}
return c;
}
Even shorter:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; list[ l ] === x && c++ );
return c;
}
Here's an implementation that uses the Array Object Prototype and has an extra level of functionality that returns the length if no search-item is supplied:
Array.prototype.count = function(lit = false) {
if ( !lit ) { return this.length}
else {
var count = 0;
for ( var i=0; i < this.length; i++ ) {
if ( lit == this[i] ){
count++
}
}
return count;
}
}
This has an extremely simple useage, and is as follows:
var count = [1,2,3,4,4].count(4); // Returns 2
var count = [1,2,3,4,4].count(); // Without first parameter returns 5
See the bottom of this post;
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(aString)
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);
You iterate on sString wich doesn't exist and not on your parameter aString.
Where is sString being declared in your function? Try with aString (or declare var sString = aString) and try again.
Please change function myF(aString) to function myF(sString)
There is a naming mistake. Here is a working copy of your code .
http://jsfiddle.net/hXarY/
You can try using "firebug" to catch such errors if you do not already do.
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(sString) // this should be sString , not aString
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);