Is It possible to in some type of way make a variable in javascript have this ---> var phone number = "(" + Array[1] + Array[2] + Array[3] ")"

80 Views Asked by At

this is my code

function createPhoneNumber(numbers)
{
  const phonelimit = [10]
  
  for(var i = 0; i < 10; i++)
    { 
      var j = i + 1
      if (i == 9)
        {
          j -= 10
          
        }
      phonelimit[i] = j
      
      
    }
   var phoneNumber = "(" + phonelimit[0] + phonelimit[1] + phonelimit[2] + ") " + phonelimit[3] + phonelimit[4] + phonelimit[5] + "-" + phonelimit[6] + phonelimit[7] + phonelimit[8] + phonelimit[9])
   return phoneNumber
}

my problem is that i am using a site called codehs for my highschool Java + javascript

and it only will allow me to submit it if it outputed using a return not a causal console.log

so some how i need to put all this junk that makes the phone number string into a variable then return the variable

I tried to do multiple toString() methods to create the whole format of the phone number thing with the numbers one variable but they didn't work

while trying to use console.log

2

There are 2 best solutions below

2
WillBeTheBestInTheFuture On

I fixed this by using the numbers variable and instead of j, I used the variable numbers and changed how the variable is returned

function createPhoneNumber(numbers) 
{ const phonelimit = [10]; 
 for (var i = 0; i < 10; i++)
    { 
      phonelimit[i] = numbers[i]; 
    }  
 numbers = `(${phonelimit[0]}${phonelimit[1]}${phonelimit[2]}) 
 ${phonelimit[3]}${phonelimit[4]}${phonelimit[5]}-${phonelimit[6]}
 ${phonelimit[7]}${phonelimit[8]}${phonelimit[9]}`; 
 return numbers;
}
0
Carsten Massmann On

Following OP's own answer the task seems to have been about formatting a telephone number. OP's answer seems to have fulfilled their requirements, although some parts seem questionable. For example, what is const phonelimit = [10] expected to do? Yes, it simply creates an array with a single element of value 10.

The following snippet will do the job in a slightly shorter way:

function createPhoneNumber(numbers){
 return numbers.replace(/(...)(...)(.{1,4}).*/,"($1) $2-$3")
}

// testing:
console.log(["0123456789","02468101214","9876541","123"].map(createPhoneNumber));

The question did not specify the min or max numbers of digits the phone number is expected to have. The above presented function createPhoneNumber() expects at least 7 digits and will ignore any digit after the tenth. This can, of course, be adjusted to requirements by changing the regular expression.