Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การกลับลำดับคำในสตริงใน JavaScript (ห้ามใช้ reverse())

เราต้องเขียนฟังก์ชันกลับลำดับคำในสตริง โดยห้ามใช้เมธอด reverse() ของอาร์เรย์

ตัวอย่าง: 'this is a string' → 'string a is this'

ตัวอย่างโค้ด

const str = 'this is a string';

const reverseWordOrder = (str = '') => {
  const strArr = str.split(' ');
  let temp = '';
  const { length } = strArr;
  for (let i = 0; i < length / 2; i++) {
    temp = strArr[i];
    strArr[i] = strArr[length - 1 - i];
    strArr[length - 1 - i] = temp;
  }
  return strArr.join(' ');
};

console.log(reverseWordOrder(str));

ผลลัพธ์

ค่าที่แสดงในคอนโซลจะเป็นดังนี้:

string a is this