I've got the following JS
var decSep_1 = true;
function radioButtons(stuff){
if( decSep_1 === true ){
return ','
}
return false
}
alert(radioButtons());
How can I make stuff in radioButtons be a part of the variable I am comparing in the if statements?
For example:
function radioButtons(stuff){
if( stuff + _1 === true ){
return ','
}
return false
}
alert(radioButtons(decSep));
I have discovered that with eval this is possible: http://jsfiddle.net/f2f87ko5/10/
var decSep_1 = true;
function radioButtons(stuff){
if(eval(stuff + "_1") === true){
return 'ytjyjju'
}
return false
}
alert(radioButtons("decSep"));
Related
Really not sure what's going on here as am new to JavaScript, but actually cannot figure it out, even after reading other posts like this one: Simple function returning 'undefined' value. For some reason, when my code is placed inside a function, it returns 'undefined' instead of true or false.
If I use the code without a function and define var a on the first line, it works OK:
var a = "wjebh ghbui ayub";
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
trueOrFalse.some(answer); // return true/false
But the moment I add it inside a function, it doesn't work.
function bThreeAfterA(a) {
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
trueOrFalse.some(answer); // return true/false
}
Even if it's put in an IIFE it doesn't work properly:
(function(){
var a = "wjebh ghbui ayub";
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
trueOrFalse.some(answer); // return true/false
})();
I feel I'm doing something very daft here that most will easily spot. Can someone explain what I'm doing wrong here? Presumably this is some sort of beginner syntax error. Links to any reading resources would be helpful too.
We've all been there.
Give this a run.
function bThreeAfterA(a) {
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
return trueOrFalse.some(answer); //ACTUALLY return true/false
}
console.log("Answer: " + bThreeAfterA("wjebh ghbui ayub")); // Returns true.
When you're operating on variables outside of the block scope, they persist. When they're inside, they vanish.
Hence, it "worked" but it didn't "work" when you have it in a function.
The code I wrote below works, but the variables I named within the each function are not defined after the function completes.
jQuery.each($myObject, function(i, val) {
ce = $(this).attr('class');
if (i === 0) {
step1complete = true;
if (/incomplete/i.test(ce)) {
var step1complete = false
}
console.log('step1' + step1complete);
} else if (i === 1) {
step2complete = true
if (/incomplete/i.test(ce)) {
var step2complete = false
}
console.log('step2' + step2complete);
} else if (i === 2) {
step3complete = true
if (/incomplete/i.test(ce)) {
var step3complete = false
}
console.log('step3' + step3complete);
}
});
if (step1complete === true && step2complete == false && step3 == false) {
console.log('Youre Just Starting Out I see');
} else {
console.log('You got one step done now theres more!');
}
However, its saying the variables I set in the each function are not defined even though I see them in the console during the loop.
Don't use var as it will scope it inside the function that is enclosed. Instead, bring them out, just the var part.
var step1complete;
var step2complete;
var step3complete;
jQuery.each($myObject, function(i, val) {
ce = $(this).attr('class');
if (i === 0) {
step1complete = true;
if (/incomplete/i.test(ce)) {
step1complete = false
}
console.log('step1' + step1complete);
} else if (i === 1) {
step2complete = true
if (/incomplete/i.test(ce)) {
step2complete = false
}
console.log('step2' + step2complete);
} else if (i === 2) {
step3complete = true
if (/incomplete/i.test(ce)) {
step3complete = false
}
console.log('step3' + step3complete);
}
});
if (step1complete === true && step2complete == false && step3 == false) {
console.log('Youre Just Starting Out I see');
} else {
console.log('You got one step done now theres more!');
}
If you don't want to pollute the global scope, use an IIFE:
(function () {
var step1complete;
var step2complete;
var step3complete;
jQuery.each($myObject, function(i, val) {
ce = $(this).attr('class');
if (i === 0) {
step1complete = true;
if (/incomplete/i.test(ce)) {
step1complete = false
}
console.log('step1' + step1complete);
} else if (i === 1) {
step2complete = true
if (/incomplete/i.test(ce)) {
step2complete = false
}
console.log('step2' + step2complete);
} else if (i === 2) {
step3complete = true
if (/incomplete/i.test(ce)) {
step3complete = false
}
console.log('step3' + step3complete);
}
});
if (step1complete === true && step2complete == false && step3 == false) {
console.log('Youre Just Starting Out I see');
} else {
console.log('You got one step done now theres more!');
}
})();
Definition:
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. It is a design pattern which is also known as Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
I need to check if file name suffix is type JavaScript (JS files end with *.js)
for that I use the following code which works
var ext = aa.getName().substr(aa.getName().lastIndexOf('.') + 1);
Now the problem is that if the file is named file2.json I'm still getting true (it's return json)
My question is if there a better way to do it i.e. given any file name like
file1.xml, file2.js, file3.json or file4.html, it will return true just for file2.
I believe this can work
function check(str){
if(str.match(/(\w*)\.js$/) == null){
console.log('false');
return false;
}
else {
console.log('true');
return true;
}
}
check('file1.xml');
check('file2.js');
check('file3.json');
check('file4.html');
let isJS = function(filename) {
return /\.js$/i.test(filename)
}
console.log(isJS("asd.json")) // false;
console.log(isJS("asdjs")) // false;
console.log(isJS("asd.js")) // true;
console.log(isJS("asd.JS")) // true;
You could check if string ends with .js with the following function:
function isJavascriptFile(str) {
var regex = /\.js$/;
var match = str.match(regex);
return match !== null;
}
According to your code you would use it like this:
var name = aa.getName();
isJavascriptFile(name);
I think for this case better not using regex,
var arr = [
'file1.xml',
'file2.js',
'file3.json',
'file4.html'
];
for(var i=0, len=arr.length; i<len; i++){
if(returnExtension(arr[i]) == 'js') {
alert('Your file is: ' + arr[i])
}
}
function returnExtension(filename){
var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
return a.pop();
}
my working example is here https://jsfiddle.net/gat8mx7y/
You've to modify your code a little bit, you're almost right:
funciton isJavascriptFile(fileName){
var ext = fileName.substr(fileName.lastIndexOf('.') + 1);
if(ext === 'js'){ return true; }
return false;
}
if(isJavascriptFile(aa.getName()) ) {
console.log("file is javascript");
}
//function GetJSName(){
var filename="sample.js";
var name = filename.split('.')[0];
alert(name);
//};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Function returns true, however if / else statement is logging false result. Any idea where I'm going wrong?
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
document.write('Login Details: ', loginDetails(username, 9), '</p>');
if(loginDetails === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
loginDetails is a function. You then test to see if it is boolean true. Funnily enough, it never will be!
I presume you actually want to run the function. You will need to cache the result in order not to run it twice:
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
var loggedIn = loginDetails(username, 9);
document.write('Login Details: ', loggedIn, '</p>');
if(loggedIn === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
What do you mean by if(loginDetails === true) ? This doesn't pass any parameters to loginDetails function.
Instead try if(loginDetails(username, 9) === true). Hope this works. Else store loginDetails(username, 9) in a variable and check whether that variable is true?
loginDetails is a function I suppose you want to check its result to be equal with true.
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
var loginDetailsResult = loginDetails(username, 9);
document.write('Login Details: ',loginDetailsResult, '</p>');
if(loginDetailsResult === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
You are checking if the reference to the function is equal to true, which will always evaluate to false. A function and a boolean are different types and therefore comparing for strict equality will always return false. I have corrected the code, so that the function is called, and the result of the function is compared, instead of the reference to the function.
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
document.write('Login Details: ', loginDetails(username, 9), '</p>');
if(loginDetails(username, 9) === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
This is my code:
var Evalcard = function(number) {
if (number == 1) {
this.name = "Ace";
this.value = 11;
}
else if (number == 11) {
this.name = "Jack";
this.value = 10;
}
else if (number == 12) {
this.name = "Queen";
this.value = 10;
}
else if (number == 13) {
this.name = "King";
this.value = 10;
}
return {this.name,this.value};
I'm pretty sure this return statement is not correct. How do you make a function return more than one value? Any help at all would be great.
In this case, you probably want to return either an array or an object literal:
return { name: this.name, value: this.value };
// later: EvalCard(...).name; EvalCard(...).number;
return [ this.name, this.value ];
// later: EvalCard(...)[0]; EvalCard(...)[1];
How about this:
return [this.name, this.value];
You could pass an object literal as you came so close to doing:
return { name:this.name, value:this.value };
or you could pass an array:
return [this.name, this.value];
Of course if your code is executed in the global context, you'll be setting name and value on the window object. If you're using Evalcard as a constructor, you wont need a return statement, the object being created will automatically be set:
var e = new Evalcard(1);
console.log(e.name); //outputs "Ace" if you remove the return statement.
Try:
return [this.name, this.value];
Try this...
function xyz() {
...
var x = 1;
var y = 'A';
return [x, y];
}
var a = xyz();
document.write('x=' + a[0] + ' and y = ' + a[1]);
Working example: http://jsfiddle.net/CxTWt/
var Evalcard = function(number) {
var evalName, evalValue;
if (number == 1) {
evalName= "Ace";
evalValue = 11;
}else if (number == 11) {
evalName = "Jack";
evalValue = 10;
}else if (number == 12) {
evalName= "Queen";
evalValue= 10;
}else if (number == 13) {
evalName= "King";
evalValue = 10;
}
return {name: evalName, value: evalValue};
}
alert(Evalcard(1).name+" "+Evalcard(1).value);
You need to change it to return an array or give keys to the object you are returning
So
return [this.name,this.value];
Or
return {name:this.name,value:this.value};
I would return an object:
return {key1:value1, key2:value2}
Then you can reference it like so:
myReturn.key1;
You can return it in a number of different ways:
Array
return [this.name,this.value];
Object
return {first:this.name, second:this.value};
String
return this.name+":"+this.value;