Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What would be the best way to format this code?
It looks a bit messy to me, in regard to indentation, etc.
if (typeof _srwc != 'undefined') {
for (var i=0; i < _srwc.length; i++){
var currentArg = _srwc[i];;
if (typeof window[currentArg[0]] == 'function') {
window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
} else {
console.log('The Setter method: "' + currentArg[0] + '" is undefined');
}
}
}
Try indenting the code inside the if, like this:
if (typeof _srwc != 'undefined') {
for (var i = 0; i < _srwc.length; i++) {
var currentArg = _srwc[i];;
if (typeof window[currentArg[0]] == 'function') {
window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
} else {
console.log('The Setter method: "' + currentArg[0] + '" is undefined');
}
}
}
Also, JSBeautifier is very useful for indenting JavaScript.
You can also use:
if (typeof _srwc != 'undefined')
{
for (var i = 0; i < _srwc.length; i++)
{
var currentArg = _srwc[i];
if (typeof window[currentArg[0]] == 'function')
{
window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
}
else
{
console.log('The Setter method: "' + currentArg[0] + '" is undefined');
}
}
}
That way all opening brackets are on the same vertical line as the closing ones and you can easily track which closing bracket is the one for a selected opening one (the first one below it on the same spacing distance). It's easier to trask the code that way if you're not using an IDE that is coloring the coresponding brackets.
When coding any language, normally entering a new block would cause indentation and exiting the same block does the opposite. (JS indentation should be 4 spaces)
ie
function xyz(){
alert("xyz");
}
and
function abc(){
if(true){
alert("true");
}else{
alert("false");
}
alert("abc");
}
..but like me if you get lazy and stop indenting using a tool like JSBeautifier whcih are available in most languages online just give it a search.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I am still a beginner to JS and I am kinda struggling on how to write multiple ifs in a correct way. For example I wrote something like this:
function calculatespot() {
//Spot 1 to 2 transfer bandage
if (spot1Selected == 1 && spot2Selected == 1) {
if (spot2Free == 1) {
localStorage.setItem('spot1Free', 1)
localStorage.setItem('spot2Free', 0)
localStorage.setItem('spot1Selected', 0)
localStorage.setItem('spot2Selected', 0)
document.getElementById('block1').style.backgroundColor = "#9eafa6"
document.getElementById('block2').style.backgroundColor = "#9eafa6"
if (user_item1 == "Bandage") {
localStorage.setItem("slot1Type", "")
localStorage.setItem("slot2Type", "Bandage")
document.getElementById('inventoryactionbtn').style.visibility = "Hidden"
document.getElementById('item1').src = "/static/images/transparant.png"
document.getElementById('item2').src = "/static/images/bandage.png"
localStorage.setItem('slot1Type', "")
localStorage.setItem('slot2Type', "Bandage")
}
}
}
This is not a very good way, but I still need all those points to match before executing the code. How could I write something like this in a better and more efficient way without having to nest all those ifs?
You can think about the following things to do:
reverse logic and return
separate logic in multiple functions
That will look like this. Which has the same functionality as your code, but less nested:
function setToSpot2Free() {
localStorage.setItem('spot1Free', 1)
localStorage.setItem('spot2Free', 0)
localStorage.setItem('spot1Selected', 0)
localStorage.setItem('spot2Selected', 0)
document.getElementById('block1').style.backgroundColor = "#9eafa6"
document.getElementById('block2').style.backgroundColor = "#9eafa6"
}
function setType2(type) {
localStorage.setItem("slot1Type", "")
localStorage.setItem("slot2Type", type)
document.getElementById('inventoryactionbtn').style.visibility = "Hidden"
document.getElementById('item1').src = "/static/images/transparant.png"
document.getElementById('item2').src = `/static/images/${type.toLowerCase()}.png`
}
function calculatespot() {
if (spot1Selected !== 1 || spot2Selected !== 1 || spot2Free !== 1) {
return;
}
setToSpot2Free();
if (user_item == 'Bandage') {
setType2(user_item);
}
}
Obviously there are more things iffy with your code, but you'll get there :)
A very important concept, at least to me, is the DRY principle. Which means, "Don't repeat yourself". If you are noticing that you are doing the same thing twice, with only a small difference in code, you can probably move this logic in its own function and set the "small difference(s)" as parameter(s) of that function.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
my code is not working at all
I need to solve this quiz
question is write convertToString as function !
this function should convert to string from parameter
ex )
let output = convertToString(120);
console.log(output); // --> '120'
let output2 = convertToString('hello');
console.log(output2); // --> 'hello'
let output3 = convertToString(true);
console.log(output3); // --> 'true'
this is what I wrote
function convertToString(anything) {
if (typeof anything === 'number' && typeof anything === 'boolean') {
let ret = anything.toString()
} else {
return anything;
}
return ret1;
}
convertToString(120);
The easiest way to convert anything is by making + operation with ""
function convertToString(anything) {
return "" + anything
}
console.log(convertToString(12));
console.log(convertToString(true));
console.log(convertToString('hello'));
console.log(convertToString(null));
console.log(convertToString(undefined));
Zero checks necessary.
function convertToString(val) {
return String(val);
// or return val.toString();
// or return '' + val;
}
console.log(convertToString(12));
console.log(convertToString(true));
console.log(convertToString('hello'));
I have a question about a codeschool.com function exercise which concluded as this...
function countE() {
var phrase = prompt("Which phrase would you like to examine?");
if (typeof(phrase) != "string") {
alert("This is not a valid entry!");
return false;
} else {
var eCount = 0;
for (var i = 0; i < phrase.length; i++) {
if (phrase.charAt(i) === 'e' || phrase.charAt(i) === 'E') {
eCount++;
}
}
alert(eCount);
return true;
}
}
countE()
So.. I wanted to test what is not a string, I wanted to get the alert "This is not a valid entry!".
But, if a prompt only returns a string then why is this
<< if (typeof(phrase) != "string") >> included in the function?
Sorry to ask this basic question here, codeschool discussion page did not give me an answer and I am very curious to know.
Thank you. J
Pressing Cancel or Esc will return null. This is the check you should be interested in.
Reference: MDN prompt.
Note: You don't need to use () with typeof. So change it to:
if (typeof phrase != "string") {
Other Scenarios
When you are expecting a number, like age or something, you can use:
if (isNaN(phrase)) {
The above might help you to decide if it is a number or not.
This question already has answers here:
How to fix jslint error 'Don't make functions within a loop.'?
(6 answers)
Closed 8 years ago.
Im using the following code which works and my question how should I write it better,since when I use EsLint I got red message that saying that dont make function without loop,currently Im new to JS so I dont know how to do that better...
for (var i = 0; i < allChildren.length; i++) {
allChildren[i].attachChange(function(){
this.getChecked() ? nSelectedChildren+=1 : nSelectedChildren-=1;
if(nSelectedChildren === 0){
oParent.toggle("Unchecked");
}
else if(nSelectedChildren === allChildren.length){
oParent.toggle("Checked");
}
else{
oParent.toggle("Mixed");
}
}
);
What EsLint meant what it should be, i think, is:
function foo(){
this.getChecked() ? nSelectedChildren+=1 : nSelectedChildren-=1;
if(nSelectedChildren === 0){
oParent.toggle("Unchecked");
}
else if(nSelectedChildren === allChildren.length){
oParent.toggle("Checked");
}
else{
oParent.toggle("Mixed");
}
}
for (var i = 0; i < allChildren.length; i++) {
allChildren[i].attachChange(foo);
}
Don't define functions within loops
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to found a simple way to format complex json files and turn it into readable html content.
The goal is to generates a set of nested boxes (html tables) containing the information of my JSON file.
Here is a sample of my json:
{"badgeGroups":
[{"name":"labAccess0", "badges" : ["AAAAAAAAAA"]},
{"name":"labAccess1", "badges" : ["1111111111","29006812B3"]}],
"inputs":
[{"name":"labDoorSecurityButton0", "state":false, "port":12}],
"outputs":
[{"name":"led0","equation":"labDoorSecurityButton0", "state":false, "port":0,"type":"GENERIC", "inputs": ...
Any ideas ?
The answer to your question depends entirely on your expected output formatting.
For example, bloopletech's json2html can parse arbitrary JSON input and a sample output can be seen over here.
If you want more customized formatting there's also json2html jQuery plugin.
All-in-all there are an infinite number of answers to your question as it's simply too broad.
function JSONtoXML(obj) {
var s = "";
var i=0;
s = s + "<" + obj[0];
var test = 0;
for(i=1;i<obj.length;i++) {
if(!(obj[i] instanceof Array) && !(typeof obj[i]==='string')) {
var obje = obj[i];
var k="";
for(prp in obje) {
k = k +" "+ prp + '="';
k = k+ obje[prp] + '" ';
}
s = s+k;
}
else if(!(typeof obj[i]==='string')){
if(test===0) {
s = s+">";
test++;
}
s = s + JSONtoXML(obj[i]);
}
else {
if(test===0) {
s = s+">";
test++;
}
s = s +obj[i];
}
}
if(test===0) {
s = s+">";
test++;
}
s = s+ "</" + obj[0] +">";
return s;
}
This will do the job to convert json to xml.
if you want better readability try some json beautifier.