Let's have a number:
let num = 12345;
Attempting to access the first character of a number will result in unexpected behavior:
let num = 12345;
if (num[0] == 1) {
console.log('+++');
} else {
console.log('---'); // it will work
}
As you should already know, the problem is that you can access the characters of a string, but not the digits of a number:
let num = 12345;
console.log(num[0]); // shows undefined
To solve the problem, let's convert our number to a string:
let num = 12345;
let str = String(num);
if (str[0] == 1) {
console.log('+++'); // it will work
} else {
console.log('---');
}
It is not necessary to introduce a new
variable, you can apply [0]
directly
to the result of the String
function:
let num = 12345;
if (String(num)[0] == 1) {
console.log('right'); // shows 'right'
} else {
console.log('wrong');
}
Let now we want to check the first digit for
the fact that it is equal to 1
or
2
. Let's write the corresponding code:
let num = 12345;
if (String(num)[0] == 1 || String(num)[0] == 2) {
console.log('+++');
} else {
console.log('---');
}
In this case, it turns out that the construct
String(num)[0]
will be repeated twice.
This, firstly, is too long, and secondly, it
is not optimal, since we will convert the
number into a string twice - the second time
it turns out to be redundant, but the program
resources are spent on it.
Let's fix the problem:
let num = 12345;
let first = String(num)[0];
if (first == 1 || first == 2) {
console.log('+++');
} else {
console.log('---');
}
Given an integer. Write a condition that will check if the last digit of this number is equal to zero.
Let the variable num
store a number.
Determine if the number is even or not.
The number will be even if the last
character is 0
, 2
, 4
,
6
, or 8
, and odd otherwise.