26.03.13 字符串反转

0 阅读1分钟

Build a String Inverter

In this lab, you will build a simple string inverter that reverses the characters of a given string.

For example, "hello" should become "olleh".

Objective:  Fulfill the user stories below and get all the tests to pass to complete the lab.

User Stories:

  1. You should create a function named reverseString that takes a string as an argument.
  2. The function should return the reversed string.

solution 1:使用for循环遍历

function reversedStr(string) {
    let reversed = ""; 
    for (let i = string.length - 1; i >= 0; i--) {
        reversed += string[i];
    }
    return reversed;
}

solution 2:使用数组的reverse方法(最快)

function reversedStr(string) {
    return string.split('').reverse().join('');
}