I have a program written in JS. It compares output of an function with number 4. However, it seems it cannot compare properly.
var myStringNotValidated = "3T-4T";
var notValidate = myStringNotValidated.substring(3, 4);
if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
//OUTPUT IS NULL, WHICH IDEALLY SHOULD BE "Value1"
Can any one guide me where am I making mistake?
You are trapped in the same mistake which most JS developers do!
There is an difference between === and == in JS. (Difference between == and === in JavaScript). Because of this, when you compare "4" with 4, it compares (String 4) with (Numeric 4), hence returning your else condition.
Solution: Just replace === with ==
var myStringNotValidated = "3T-4T";
var notValidate = myStringNotValidated.substring(3, 4);
if(notValidate == 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
https://jsfiddle.net/pfrvn485/
It depends, if you want to check if notValidate is a string:
var myStringNotValidated = "3T-4T";
var notValidate = myStringNotValidated.substring(3, 4);
if(notValidate === "4") // Change here
{
console.log("Value1");
}
else
{
console.log("null");
}
if you want to check if notValidate is a number, use parseInt():
var myStringNotValidated = "3T-4T";
var notValidate = parseInt(myStringNotValidated.substring(3, 4)); // Change here
if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
Your if condition is wrong if(notValidate === 4) checks 4 as string. either you can use if(notValidate=='4') or convert it to number & check.
This is because === compares both value and type. In your program, noValidate contains a value of 4 but its type is string and you are comparing it with 4 whose type is number.
You can either use == or typecast noValidate to number.
var myStringNotValidated = "3T-4T";
var notValidate = Number(myStringNotValidated.substring(3, 4));
console.log(typeof notValidate);
if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
You're comparing the string("4") with the int type(4). Need to be converted to an integer before comparing.
var myStringNotValidated = "3T-4T";
var notValidate = parseInt(myStringNotValidated.substring(3, 4));
if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
Try this :
var myStringNotValidated = "3T-4T";
var notValidate = myStringNotValidated.substring(3, 4);
if(notValidate === "4")
{
console.log("Value1");
}
else
{
console.log("null");
}
Related
I really thought I had this code correct. I am trying to calculate basketball score with free throws, 2 pointers and 3 pointers. The output when I console.log the totalBasketballScore ends up being 'All entries must be numbers' and undefined. What do I need to change so I get the score when I put the 3 values in the parameters?
function totalBasketballScore(numberFreeThrows, numberMidRange, numberThreePointers) {
const freeThrows = 1;
const midRange = 2;
const threePointers = 3;
if (typeof numberFreeThrows === 'number' && numberMidRange === 'number' && numberThreePointers === 'number') {
let totalFreeThrows = freeThrows * numberFreeThrows;
let totalMidRange = midRange * numberMidRange;
let totalThreePointers = threePointers * numberThreePointers;
let gameTotal = totalFreeThrows + totalMidRange + totalThreePointers;
return gameTotal;
} else {
console.log('All Entries Must Be a Number');
}
}
console.log(totalBasketballScore(1, 2, 4));
Another approach that can be used is isNaN(). isNaN can be used to check if the value is Not a Number. If isNaN() returns false, the value is a number.
function totalBasketballScore(numberFreeThrows, numberMidRange, numberThreePointers) {
const freeThrows = 1;
const midRange = 2;
const threePointers = 3;
if(isNaN(numberFreeThrows)=== false && isNaN(numberMidRange)=== false && isNaN(numberThreePointers)=== false) {
let totalFreeThrows = freeThrows * numberFreeThrows;
let totalMidRange = midRange * numberMidRange;
let totalThreePointers = threePointers * numberThreePointers;
let gameTotal = totalFreeThrows + totalMidRange + totalThreePointers;
return gameTotal;
} else {
console.log('All Entries Must Be a Number');
}
}
console.log(totalBasketballScore(1, 2, 4));
You should use typeof per each parameter, like this:
if(typeof numberFreeThrows === 'number' && typeof numberMidRange === 'number' && typeof numberThreePointers === 'number'){
} else {
}
I know how modulus works in general, but it is not clear to me how the operator handles strings.
Recently, I had to write a script which checks if a name (string) contains an even number of letters. This actually worked, using modulus 2 and checking if result was 1 or 0:
function isNameEven(firstName) {
if (firstName % 2 === 0) {
return true;
}
else {
return false;
}
}
So I'm assuming the letters in the string were counted?
The result is always NaN
const oneLetter = "a";
const twoLetters = "ab";
const threeLetters = "abc";
console.log(oneLetter % 2);
console.log(twoLetters % 2);
console.log(threeLetters % 2);
Your function doesn't work if you pass it a string that can't be implicitly converted to a number that isn't NaN.
function isNameEven(firstName) {
if (firstName % 2 === 0) {
return true;
} else {
return false;
}
}
const oneLetter = "a";
const twoLetters = "ab";
const threeLetters = "abc";
console.log(isNameEven(oneLetter));
console.log(isNameEven(twoLetters));
console.log(isNameEven(threeLetters));
You could check the length property of the string though.
function isNameEven(firstName) {
if (firstName.length % 2 === 0) {
return true;
} else {
return false;
}
}
const oneLetter = "a";
const twoLetters = "ab";
const threeLetters = "abc";
console.log(isNameEven(oneLetter));
console.log(isNameEven(twoLetters));
console.log(isNameEven(threeLetters));
I want to loop through an array and check if each element is a number OR a string that could potentially turned into a number (e.g. "42"). If it can be "converted" then the element should be stored in a new array.
This is my code where I push all converted elements into a new array. Notice: I also want to count how many elements were "converted" from a string into a number and how many were not.
function numberConverter(arr) {
var converted = []
var counterConverted = 0
var counterNotConverted = 0
for (var c of arr) {
if (typeof c == "string" && Number(c) == "number") {
counterConverted++;
parseInt(c, 10);
converted.push(c)
} else {
counterNotConverted++
}
}
if (counterConverted == 0) {
return "no need for conversion"
} else {
return counterConverted + " were converted to numbers: " + converted + "; " + counterNotConverted + " couldn't be converted"
}
}
I know that my if condition
if(typeof c == "string" && Number(c) == "number")
is flawed logically, but I can't make up why.
Thanks for any hints and please explain it in beginner terms.
You can test if a string could be converted to a number like so:
val !== "" && Number.isNaN(Number(val)) === false
And the code could be written like so:
function numberConverter(arr) {
var converted = [];
var notconverted = [];
arr.forEach(function(val) {
if (typeof val === "number") {
converted.push(val);
} else if (typeof val === "string" && val !== "" && Number.isNaN(Number(val)) === false) {
converted.push(Number(val));
} else {
notconverted.push(val);
}
});
console.log("converted", converted);
console.log("not converted", notconverted);
}
numberConverter([0, "1", "", "123-foo", undefined, null, true, [], {}]);
The best solution is to use a functional approach to the code rather than an imperative one.
let arrayNumbers = ["Vadim", 99, {}, [], "100", "55AA", "AA55", Infinity, "false", true, null, -65.535, 2E1, "2E2"].filter( value => value !== null && value != Infinity && value !== '' && !isNaN(Number(value)) && !['boolean','array','object'].includes(typeof value)).map(value => +value);
console.log('Was Converted to Numbers:', arrayNumbers);
You need to check typeof string and isNaN in ESLint way (Number.isNaN(Number())).
function numberConverter(arr) {
const converted = [];
let counterConverted = 0;
for (let i = 0; i < arr.length; i += 1) {
const str = arr[i];
if (str && typeof str === 'string' && !Number.isNaN(Number(str))) {
const number = parseInt(str, 10);
converted.push(number);
counterConverted += 1;
}
}
const counterNotConverted = arr.length - converted.length;
if (counterConverted === 0) {
return 'No need for conversion.';
}
return `${counterConverted} were converted to numbers: ${converted.join(',')}; ${counterNotConverted} couldn't be converted`;
}
console.log(`'${numberConverter(['id', null, {}])}'`); // No need for conversion.
console.log(`'${numberConverter(['1', '-1', 'val'])}'`); // 2 were converted to numbers: [1,-1]; 1 couldn't be converted
console.log(`'${numberConverter(['1', '-1', '0', '1.5', 'val'])}'`); // 4 were converted to numbers: [1,-1,0,1]; 1 couldn't be converted
I was trying to solve the following coding exercise.
We have two special characters. The first character can be represented
by one bit 0. The second character can be represented by two bits (10
or 11).
Now given a string represented by several bits. Return whether the
last character must be a one-bit character or not. The given string
will always end with a zero.
example:
Input: bits = [1, 0, 0] Output: True
Below is my solution for the above challenge. Why is this returning undefined? If I use [1,0,1,0] as input, it should return true but I am getting undefined. I am explicitly writing true in the return statement and not the results of a variable.
var isOneBitCharacter = function(bits) {
console.log(bits);
var length = bits.length;
if (length == 1) {
return true;
}
if (length == 0) {return false;}
if (length == 2 && bits[0] === 1) {
return false;
}
if (bits[0] === 1) {
isOneBitCharacter(bits.slice(1));
} else {
isOneBitCharacter(bits.slice(2));
}
};
isOneBitCharacter([1,0,1,0]);
I guess you are missing returns. Here is adjusted code:
var isOneBitCharacter = function(bits) {
console.log(bits);
var length = bits.length;
if (length == 1) {
return true;
}
if (length == 0) {return false;}
// added return here and next statements
if (length == 2 && bits[0] === 1) {
return false;
}
if (bits[0] === 1) {
return isOneBitCharacter(bits.slice(1));
} else {
return isOneBitCharacter(bits.slice(2));
}
};
isOneBitCharacter([1,0,1,0]);
In this function the user selects a value in the dropdown menu and whatever value is selected, it would change var B to its corresponding value.
function test(){
var A = ["", "A", "B", "C"];
var B = document.getElementById("myfile");
if(A.value = "A"){
B.selectedIndex = [2];
}
else if(A.value = "B"){
B.selectedIndex = [4];
}
else if(A.value = "C"){
B.selectedIndex = [1];
}
}
The problem I am having is that every time I select B or C, it always defaults to index [2] and not [4] or [1].
You're assigning when you mean to compare. Use ==, not =, for comparison.
if(A.value == "A"){
B.selectedIndex = [2];
}
else if(A.value == "B"){
B.selectedIndex = [4];
}
else if(A.value == "C"){
B.selectedIndex = [1];
}
= is assignment
== is test for equality for content
=== is test for equality for content and data type
In your case, = is certainly a typo. I'd recommend using === for maximum program stability.
Some folk tend to write "A" == A.value so a misplaced assignment gives you a syntax error.
You're assigning the value in your ifs not testing it. This will return the value that is assigned. The if condition will be true unless the following values are assigned and therefore returned, false, 0, an empty string, null, undefined or NaN. That's why you are entering the block of the first if statement.
Change the single equals to double or triple equals.
if(A.value == "A"){
B.selectedIndex = [2];
}
else if(A.value == "B"){
B.selectedIndex = [4];
}
else if(A.value == "C"){
B.selectedIndex = [1];
}
Use == not =
Your statement checks if its possible to set the value.(Every time...)