signed

QiShunwang

“诚信为本、客户至上”

JavaScript 实战 02

2020/12/26 10:57:38   来源:

题目

Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.

测试:

describe('Basic tests', () => {
  Test.assertEquals(createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), "(123) 456-7890");
  Test.assertEquals(createPhoneNumber([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), "(111) 111-1111");
  Test.assertEquals(createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), "(123) 456-7890");
});

我的答案:

function createPhoneNumber(numbers){
  numbers.splice(0, 0, '(');
  numbers.splice(4, 0, ')');
  numbers.splice(5, 0, ' ');
  numbers.splice(9, 0, '-');
  
  let str = numbers.join('');
return str;
}

Clever Answer:Solutions 下比较靠前的答案

function createPhoneNumber(numbers){
  var format = "(xxx) xxx-xxxx";
  
  for(var i = 0; i < numbers.length; i++)
  {
    format = format.replace('x', numbers[i]);
  }
  
  return format;
}