Javascript - Continue statement not working? - javascript

Im currently learning about break and continue statements. It prints the 1st array, the 2nd array runs the alert like it suppose to, but the third one doesn't run, when i use the continue statement. Maybe im not doing it right? some guidance for a newbie would be nice.
Im using JSBin to run this.
p.s. im learning from the "Begining Javascript" book
Thanks
var n = [233, "john", 432];
var nIndex;
for (nIndex in n) {
if (isNaN(n[nIndex])) {
alert(n[nIndex] + " is not a number");
continue;
}
document.write(n[nIndex] + " ");
}

Continue does not work in :
for(i in array) {}
it works for for(i=0; i<n; i++){}

This is how you iterate over the elements of an array:
var data = [233, "john", 432];
for (var i = 0; i < data.length; ++i) {
if (isNaN(data[i])) {
alert(data[i] + " is not a number");
continue;
}
document.write(data[i] + " ");
}
By the way, you can remove the continue statement and instead use else on the alternate instructions:
var data = [233, "john", 432];
for (var i = 0; i < data.length; ++i) {
if (isNaN(data[i])) {
alert(data[i] + " is not a number");
} else {
document.write(data[i] + " ");
}
}
That's logically equivalent and you may find it easier to read.

Related

Can't create an opportune return for my function

I have to create a function that checks if a word is palindrome or not. My reasoning is to break down the word letter by letter, normal and reverse, and then compare the two results to determine if a word is a palindrome or not. With an if - else I give the user an alert that tells perfectly the result. Now, I've learned that most of the functions must have a return with a variable that contains that desired result.
In this case I really can't have this, I think it can work perfectly this way. I tried with
var palindromeResult = (leftToRightWord == rightToLeftWord) ? 'true':'false';
console.log(palindromeResult);
return palindromeResult;
but it works only for the developer if he reads the console.log in the console, but it's a bad solution for me... Have you got any better idea than this? Below my full function code
function isPalindrome(wordToCheck) {
for(var i = 0; i < wordToCheck.length; i++) {
var leftToRightWord = wordToCheck[i];
console.log('Left ' + leftToRightWord);
}
for(var j = wordToCheck.length - 1; j >= 0; j--) {
var rightToLeftWord = wordToCheck[j];
console.log('Right ' + rightToLeftWord);
}
if ( leftToRightWord === rightToLeftWord) {
alert('La parola è palindroma');
} else {
alert('La parola non è palindroma');
}
Edit: At the end I changed a lot my code for a better legibility.
//Data
var userWord;
//I ask a word to the user
do {
userWord = prompt("Dimmi una parola");
} while (userWord.length === 0)
//Here the result of the function is saved and it can be reused
var functionResult = isPalindrome(userWord);
console.log (functionResult);
//Function to know if the word inserted is a palindrome or not
//the cycle with rightToLeft reverse the word so it can be compared to the normal word
//A pop-up will give the solution so it can be seen clearly on your screen
//The function result will ben saved outside the function in var functionResult so it can be seen with a console.log or reused for whatever use
function isPalindrome(wordToCheck) {
var rightToLeftWord = '';
for(var j = wordToCheck.length - 1; j >= 0; j--) {
rightToLeftWord = rightToLeftWord + wordToCheck[j];
}
console.log(rightToLeftWord);
var palindromeResult = wordToCheck == rightToLeftWord;
alert(palindromeResult);
return palindromeResult;
}
Now the cycle with for doesn't have problems anymore as you've pointed out to me and it correctly recognize if a word is a palindrome or not.
See the snippet. The function returns the answer and then you can alert it, assign it to a variable, echo it on the page and so on. I'm not pretty sure about your algorithm since it is telling me that 'abracadabra' is palindrome but it is not. RTL the sequence of the letters is wrong!
function isPalindrome(wordToCheck) {
for (var i = 0; i < wordToCheck.length; i++) {
var leftToRightWord = wordToCheck[i];
console.log('Left ' + leftToRightWord);
}
for (var j = wordToCheck.length - 1; j >= 0; j--) {
var rightToLeftWord = wordToCheck[j];
console.log('Right ' + rightToLeftWord);
}
if (leftToRightWord === rightToLeftWord) {
return 'La parola è palindroma';
} else {
return 'La parola non è palindroma';
}
}
alert(isPalindrome('abracadabra'));

Parsing some JSON

I have a complex JSON file that needs parsing and my loop skills (or more precisely, the lackthereof), are really failing me.
I have the following xml file, and I am trying to get all elements on one row. In my perfect world (in no particular order)...
sku #, length, width, image, description, attribute value 1, attribute value 2, attribute value 3, etc.
The JSON file is as follows:
var json = {
"product":[
{
"shipdata":{
"_length":"2in",
"_width":"2in",
},
"sku":"90245",
"brand":"Brandy",
"image":"shirt.jpg",
"description":"description",
"attributes":{
"attribute":[
{
"_name":"Color",
"_value":"Black",
},
{
"_name":"Gender",
"_value":"Mens",
},
{
"_name":"Size",
"_value":"L",
},...
So, my intended result is:
90245, Brandy, Black, Men's, L, shirt.jpg, 2in, 2in
But when I loop like the following, I only get the first result for "name". Admittedly, I'm a newb, but if anyone can push me in the right direction or show a proof of concept, it would be so so appreciated. Thanks in advance / feel horrible to even ask such a low level question.
for(var l = 0; l < json.product[i].attributes.attribute.length; l++) {
var xxx = (json.product[i].attributes.attribute[l]['_name']);
}
$('body').append(xxx);
if you don't mind using lodash, this should help you:
var res=[];
_.each(json.product, function(p) {
res.push(p.brand);
res.push(p.sku);
_.each(p.attributes.attribute, function(at) {
res.push(at._value);
});
});
console.log(res.join(','));
//Brandy,90245,Black,Mens,L
working fiddle
EDIT: My solution is obviously not as good as scottjustin5000 's. I'm trying to explain the detailed steps on analyzing this problem.
You want to output a string from the JSON data. So we should break the parts of the string and process one by one.
90245, Brandy, Black, Men's, L, shirt.jpg, 2in, 2in
"sku", "brand", attribute, attribute, attribute, "image", "_length", "_width"
Let's start.
function parseJSONToLine(product) {
var line = "";
line = line + product["sku"] + ", ";
line = line + product["brand"] + ", ";
line += getAllAttributes(product);
line = line + product["image"] + ", ";
line = line + product["shipdata"]["_length"] + ", ";
line = line + product["shipdata"]["_width"];
return line;
}
products = json["product"];
for (var i = 0; i < products.length; i++) {
console.log(parseJSONToLine(products[i]));
}
This part is just assembling the line your want part by part. For the attributes, we need another loop:
function getAllAttributes(product) {
var attrStr = "";
var attrsDict = {};
var attrsOrder = ["Color", "Gender", "Size"];
var attrList = product["attributes"]["attribute"];
// loop through every attribute and put it in dictionary
for (var i = 0; i < attrList.length; i++) {
attrsDict[attrList[i]["_name"]] = attrList[i]["_value"];
}
for (var i = 0; i < attrsOrder.length; i++) {
attrStr = attrStr + attrsDict[attrsOrder[i]] + ", ";
}
return attrStr;
}
The last part is to put the line produced into your HTML. Just the $(body') line with:
$('body').append('<p>' + line + '</p>');
That's it. The point to solve this problem is to know what the line is consisted of. Then try to get the values in the JSON object one by one. When meeting something seems to be complicated, just try to write out the code and modify according to the output. console.log() is very helpful on this.
The reason of why your code doesn't work is, your JSON data contains not only arrays but also objects. You have to take them apart.
If you need further explanation on the snippet, comment me.
JSFiddle: https://jsfiddle.net/aresowj/g9wuLg28/
According to your JSON structure and the output you want, I'll suggest to do the following:
var output = Array(json.product.length); // will be an array of string
for(var i = 0; i < json.product.length; i++) {// loop on each product
output[i] = json.product[i].sku +', '+json.product[i].brand; // according to your question, seems that you want these 2 things first
for(var j = 0; j < json.product[i].attributes. attribute.length; j++){ // then we loops on the attributes
output[i] += ', ' +json.product[i].attributes. attribute[j]._name;
}
output[i] += ', ' +json.product[i].shipdata._length + ', ' + json.product[i].shipdata._width; // last we append to the string the with and height data
}
$('body').append(output)
var json = {
"product":[
{
"shipdata":{
"_length":"2in",
"_width":"2in",
},
"sku":"90245",
"brand":"Brandy",
"image":"shirt.jpg",
"description":"description",
"attributes":{
"attribute":[
{
"_name":"Color",
"_value":"Black",
},
{
"_name":"Gender",
"_value":"Mens",
},
{
"_name":"Size",
"_value":"L",
}
]
}
}
]
};
var output = Array(json.product.length); // will be an array of string
for(var i = 0; i < json.product.length; i++) {// loop on each product
output[i] = json.product[i].sku +', '+json.product[i].brand; // according to your question, seems that you want these 2 things first
for(var j = 0; j < json.product[i].attributes. attribute.length; j++){ // then we loops on the attributes
output[i] += ', ' +json.product[i].attributes. attribute[j]._name;
}
output[i] += ', ' +json.product[i].shipdata._length + ', ' + json.product[i].shipdata._width; // last we append to the string the with and height data
}
$('body').append(output)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A solution using Array.map:
var res = json.product.map(function (p) {
return [p.sku, p.brand].concat(p.attributes.attribute.map(function (at) {
return at._value;
}))
});
res.forEach(function (r) { console.log(r.join(', ')) });
https://jsfiddle.net/xve4agp6/1/

show the location of each occurence of the character 'e' in a string

WORKED UP AN ANSWER. SCROLL TO BOTTTOM
I'm having trouble trying to display this character. For the most part, I have the code structure set but I'm having trouble storing the correct values in the arrays. Getting stuck and burned out!
wordString = 'i, always, have, fruit, for, breakfast, consisting, of, a, small, fruit, bowl, with, yogurt, on, top, of, the, fruit, but, if, it, is, doughnuts, I, always, have, two, sometimes, they, have, sprinkles, and, sometimes, not, i, never, have, cereal, or, eggs, this, breakfast, regimen, is, very, healthy, especially, the, doughnuts.';
var wordPosition = [];
var letterAppearance = wordString.match(/e/g);
var positionStart = 0;
for(i = 0; i <= letterAppearance.length; i++) {
positionStart = wordPosition[i];
if(positionStart === 0) {
positionString = wordString.substr(positionStart, wordString.length)
} else {
positionString = wordString.substr(wordPosition[i], wordString.length)
}
wordPosition[i] = positionString.indexOf('e');
}
Thanks for the help ahead of time
EDIT
Okay so I've worked on this a bit more and have something a bit simpler but have not yet gotten it to work. My values are not quite correct other than the 1st couple in the array
var wordPosition = [];
var letterAppearance = wordString.match(/e/g);
var positionStart = 0;
for( i = 0; i <= letterAppearance.length; i++){
wordPosition[i] = wordString.indexOf('e')+ positionStart;
positionStart = wordPosition[i];
}
Heres are the values that I get.
14,28,42,56,70,84,98,112,126,140,154,168,182,196,210,224,238,252,266,280,294,308,322,336,350,364
EDIT ANSWER FOUND
Okay, after working on it some more I've gotten the correct code for the answer. Here it is in the simplest form.
locations = " letter 'e' occurs at locations: ";
for (i = 0; i <= wordString.length; i++){
character = wordString.substr(i,1);
if(character === 'e'){
locations = locations + i.toString() + ",";
}
}
I think that's too complicated to search for just some 'e' positions. You can try this:
for (int i=0; i < /*string lenght*/ ; i++)
if (/*String char at i*/ == 'e')
/*Store position */
Okay, after working on it more, I've found the answer in it's simplest form.
locations = " letter 'e' occurs at locations: ";
for (i = 0; i <= wordString.length; i++){
character = wordString.substr(i,1);
if(character === 'e'){
locations = locations + i.toString() + ",";
}
}
Here is the output.
letter 'e' occurs at locations: 14,31,108,160,171,175,181,188,198,210,214,227,229,236,240,242,251,265,275,279,288,294,302,305,316,
You can try this:
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i+1);
}

For loop in Javascript runs only once

Here is my code. I do not quite understand why the for loop runs only once, both inner and outer. nodeList.length and innerNodeList.length show appropriate values when I generate alert messages. I see that both i and j do not increment beyond 0. Kindly point out anything wrong with the code.
function getCategoryElements() {
var newCategoryDiv = document.getElementById("category");
var nodeList = newCategoryDiv.childNodes;
for (var i = 0; i < nodeList.length; ++i) {
var innerNodeList = nodeList[i].childNodes;
alert("innerNodeList Length" + innerNodeList.length.toString());
for (var j = 0; j < innerNodeList.length; ++j) {
if (innerNodeList[j].nodeName == "SELECT") {
alert("inside select Node value " + innerNodeList[j].nodeValue.toString());
document.getElementById("newCategories").value =
document.getElementById("newCategories").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
} else if (innerNodeList[j].nodeName == "TEXTAREA") {
document.getElementById("newCategoriesData").value =
document.getElementById("newCategoriesData").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
}
}
}
}
var newCategoryDiv, nodeList, innerNodeList, innerNode, i, j;
newCategoryDiv = document.getElementById("category");
nodeList = newCategoryDiv.childNodes;
for (i = 0; i < nodeList.length; ++i) {
innerNodeList = nodeList[i].childNodes;
alert("innerNodeList Length" + innerNodeList.length.toString());
for (j = 0; j < innerNodeList.length; ++j) {
innerNode = innerNodeList[j];
if (innerNode.nodeName === "SELECT") {
alert("inside select Node value " + innerNode.nodeValue.toString());
document.getElementById("newCategories").value += '<%=delimiter%>' + innerNode.nodeValue;
} else if (innerNode.nodeName === "TEXTAREA") {
document.getElementById("newCategoriesData").value += '<%=delimiter%>' + innerNode.nodeValue;
}
// Will this work?
alert('Does this alert appear');
}
}
I took the liberty to refactor your code and clean it up a little bit. In case you're not aware, all variables have function scope in Javascript, so no matter where you declare them within a single function, Javascript treats them as if the variable declaration is the first statement.
It appears that your code is syntactically correct, and so I think that the most logical place to look for a problem is that there could be an error occurring after the last alert function call.
In order to check this, try adding another alert function call to the end of the inner loop. If it doesn't run, you'll know this is the case.

'for loop' and possible syntax error

Here is my current javascript. I know that it worked until I added the 'for loop'. The point of the for loop is to switch letters. As it stands, its checking to see if groups of 3 are equal to one letter. I will fix that later, but I know there must be a syntax error, as the buttons don't fade as my mouse moves over them. I know this is a stupid question and I'll kick myself when I see the error, but I'm tired and can't find it for my life right now. Also, is this for loop a valid way of changing letters? Is that the correct way to set an array value to the new letter?
Here is the script.js:
$(document).ready(function() {
$('#button_translate').mouseenter(function() {
$('#button_translate').fadeTo('fast', 1);
});
$('#button_translate').mouseleave(function() {
$('#button_translate').fadeTo('fast', 0.7);
});
$('#button_clear').mouseenter(function() {
$('#button_clear').fadeTo('fast', 1);
});
$('#button_clear').mouseleave(function() {
$('#button_clear').fadeTo('fast', 0.7);
});
$('#button_translate').click(function() {
var dna = $('input[name=dna]').val();
var dna = dna.toUpperCase();
function allBases(text) {
var bases = /^[ACGT]+$/;
if(text.match(bases)) {
var arr = text.match(/.{1,1}/g);
/*document.write(arr + " is a DNA sequence.");*/
for (var i = 0; i < (dna.length); i++) {
if (arr[i]==='A') {
arr[i]='U'
}else if (arr[i]==='C') {
arr[i]='G'
}else if (arr[i]==='G') {
arr[i]='C'
}else if (arr[i]==='T') {
arr[i]='U'
}else{
document.write(dna + " is not a real DNA sequence. Error Code 2");
}
}
document.write(dna + " is the translated mRNA strand!");
}else{
document.write(dna + " is not a real DNA sequence.");
}
}
allBases(dna);
});
});
for (var i=0; i>=((dna.length) / 3); i++) {
you probably want the loop condition to be i less than dna.length
for (var i = 0; i < (dna.length/3); i++) {
you have an unclosed ( in the for loop
for (var i=0; i>=(dna.length) / 3); i++) { // extra ( in i>=((dna.length) / 3)

Categories

Resources