Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách chuyển từ thành số nguyên trong JavaScript

Viết hàm nhận chuỗi, trả về số tương ứng. Ví dụ: "one five seven eight" -> 1578, "Two eight eight eight" -> 2888.

Tách chuỗi theo khoảng trắng, duyệt mảng từ, cộng số tương ứng vào kết quả.

Ví dụ

const wordToNum = (str) => {
  const legend = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
  return str.toLowerCase().split(" ").reduce((acc, val) => {
    const index = legend.indexOf(val);
    return (acc * 10 + index);
  }, 0);
};

console.log(wordToNum('one five six eight'));
console.log(wordToNum('zero zero two zero eight'));
console.log(wordToNum('eight six seven five'));

Kết quả

Đầu ra trong console sẽ là:

1568 208 8675