why this code returns a value of the i=0 only(see the terminal)?
when I use console.log in each if statement instead of the return keyword, I get all the values for each value of ‘i’ .
It looks like you are trying to convert letters into binary.
If that is true, then I think an easier solution would be to loop through the arr, get the charCode and then use the toString method to convert it to binary.
no that is not what i am trying to do.
i am trying to get all the numbers printed into one horizontal line that is easy to read, like an array for example. i think I asked you the wrong question.
No,not some generated binary numbers that some javascript method can do, all i want is that the numbers on myBinary array be printed everytime the if statements are true, than take those printed results which are separate in the console and put them in one array.
I guess the quickest fix would be to add the push statements inside the conditions.
It is a little repetitive and there is probably a much better solution but it would give you the result you are looking for.
var myPhrase = 'CADB';
var myAlpha = ['A','B','C','D'];
var mybiary = ['01','1000','1010','100'];
var myArray = [];
function test(){
for (let i=0;i<=4;i++) {
if(myPhrase[i] == myAlpha[0]){
console.log(mybiary[0])
myArray.push(mybiary[0])
}
if(myPhrase[i] == myAlpha[1]){
console.log(mybiary[1])
myArray.push(mybiary[1])
}
if(myPhrase[i] == myAlpha[2]){
console.log(mybiary[2])
myArray.push(mybiary[2])
}
if(myPhrase[i] == myAlpha[3]){
console.log(mybiary[3])
myArray.push(mybiary[3])
}
}
}
test();
console.log(myArray);
One way I would restructure this would be to create an object for the letters and binary numbers and then loop through that object and push results to an array.
const alphaObj = {
C: "1010",
A: "01",
D: "100",
B: "1000"
};
const binaryArr = [];
for (const letter in alphaObj) {
console.log(alphaObj[letter]);
binaryArr.push(alphaObj[letter]);
}
console.log(binaryArr);
Yeah that could work too. But for me personally I think the cleaner option would be to create an object with the values and then loop through it. It just looks cleaner than writing a whole bunch of if statements