my task is:
Your task is correct the errors in the digitised text. You only have to handle the following mistakes:
S is misinterpreted as 5
O is misinterpreted as 0
I is misinterpreted as 1
my code:
function correct(string) {
for (var i = 0; i < string.length; i++) {
if (string[i] === 5) {
string[i] = "S";
}
if (string[i] === 0) {
string[i] = "O";
}
if (string[i] === 1) {
string[i] = "I";
}
}
return string;
}
help me… some tips…
You’re using the strict comparison operator ===
between different types, numbers and strings
You didn’t tell us what errors you’re having, and in future you should do, but I suspect if you used ==
instead or changed the numbers to strings it’d end up right
for example correct(L0ND0N)
should return LONDON
As @gebulmer says, you’re doing a strict comparison, and you have an array of strings. There will never be a 0
or a 1
or a 5
in the array because what you have are strings, not numbers: ie there might be a "5"
, but never a 5
. x === y
is checking if x exactly equals y (and is normally what you should use). x == y
will do coercion, so will work in this case I think.
1 Like
function correct(string) {
for (var i = 0; i < string.length; i++) {
if (string[i] == 5) {
string[i] = S;
}
if (string[i] == 0) {
string[i] = O;
}
if (string[i] == 1) {
string[i] = I;
}
}
return string;
}
it still has ReferenceError: I is not defined
. what does it mean???
It means there are no Variable declared by name I
.
If you use I
directly then it is consider as a variable to use
I
as a char value you have to enclose them between '
or "
…
Then the modified code will look like this
function correct(string) {
for (var i = 0; i < string.length; i++) {
if (string[i] == 5) {
string[i] = ‘S’;
}
if (string[i] == 0) {
string[i] = ‘O’;
}
if (string[i] == 1) {
string[i] = ‘I’;
}
}
return string;
}
I’ve tried in such way… but it doesn’t work. =(
Can you share me the link for the exercise
Later I’ll try to push
to a new string … maybe it will be better
You have to treat number as character also then your function will work
Then the modified code will look like this
function correct(string) {
for (var i = 0; i < string.length; i++) {
if (string[i] == ‘5’) {
string[i] = ‘S’;
}
if (string[i] == ‘0’) {
string[i] = ‘O’;
}
if (string[i] == ‘1’) {
string[i] = ‘I’;
}
}
return string;
}
no
… failed.
You cannot modify a string variable . I think thats why your solution is not working .
I think js treat it as a constant .
Here is the solution you can try 
function correct(string) {
string = string.split(’’);
for (var i = 0; i < string.length; i++) {
if (string[i] == “5”) {
string[i] = “S”;
}
if (string[i] == “0”) {
string[i] = “O”;
}
if (string[i] == “1”) {
string[i] = “I”;
}
}
return string.join(’’);
}
1 Like