简体   繁体   中英

How do I get my 'for loop' to return the characters I am trying to push?

I am learning the fundamentals of JavaScript currently but am realizing there are definite gaps in my knowledge. I recently started attempting challenges on Codewars when this issue became much more apparent. My latest struggle has been attempting to get this 'for loop' to push characters into an array of numbers in order to format it like a phone number. As many different solutions as I have tried, none of them actually do what I am trying to accomplish. Any help figuring out exactly where I'm going wrong here and what holes are in my logic would be appreciated. My best attempt is this:

 const createPhoneNumber = (phoneNumber) => { let formattedNumber = []; formattedNumber.push(phoneNumber) for (let i = 0; i < formattedNumber.length; i++) { if (formattedNumber[i] === 0) { formattedNumber.push('(') } if (formattedNumber[i] === 2) { formattedNumber.push(')') } if (formattedNumber[i] === 5) { formattedNumber.push('-') } } return(formattedNumber.toString()); } console.log(createPhoneNumber(1234567890));

Some feedback:

  • You're inserting one item into the array formattedNumber.push(phoneNumber) then looping through it, so there's only one iteration
  • Instead, convert the number to a string and iterate through that
  • The check formattedNumber[i] === 0 is comparing the value to 0 (this check fails and is why your function is returning the unformatted phone number) but you want to compare the index , so change this to i === 0
  • At the end of the function you're using toString() to join the characters back together but this will include commas between values, instead use .join('')

 const createPhoneNumber = (phoneNumber) => { const phoneNumberStr = (phoneNumber).toString(); let formattedNumber = []; for (let i = 0; i < phoneNumberStr.length; i++) { if (i === 0) { formattedNumber.push('(') } if (i === 2) { formattedNumber.push(')') } if (i === 5) { formattedNumber.push('-') } formattedNumber.push(phoneNumberStr[i]); } return(formattedNumber.join('')); }; console.log(createPhoneNumber(1234567890))

Also, you can use .reduce() to achieve the same thing, it's a convenient function that iterates through an array, and passes a value from one iteration to the next:

 const createPhoneNumber = (phoneNumber) => (phoneNumber).toString().split('').reduce((acc, char, i) => { let pre = ''; if (i == 0) { pre = '('; } if (i == 2) { pre = ')'; } if (i == 5) { pre = '-'; } return `${acc}${pre}${char}`; }, ''); console.log(createPhoneNumber(1234567890));

BTW, I think your question was downvoted because you didn't provide an expected output or more details of the error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM