#100daysofMiva 코딩 챌린지 8일차에는 한 언어를 다른 언어로 번역하는 간단한 번역기 모델을 작업했습니다.
JS에요 마법이에요✨?
? 언어 번역기 스크립트 문서
개요
이 JavaScript 코드는 재미있는 대화형 언어 번역기를 만들기 위해 설계되었습니다! MyMemory API를 활용하여 서로 다른 언어 간에 텍스트를 번역하고 언어를 교환하고, 번역을 복사하거나, 텍스트를 소리내어 말해 줄 수도 있습니다. ??
특징
- ? 언어 선택: 사용자는 암하라어에서 줄루어까지 다양한 언어 중에서 선택할 수 있습니다!
- ? 언어 전환: 버튼 클릭 한 번으로 소스 언어와 대상 언어를 쉽게 전환할 수 있습니다.
- ? 텍스트 음성 변환: 선택한 언어로 원본 또는 번역된 텍스트를 들어보세요.
- ? 클립보드에 복사: 한 번의 클릭으로 원본 또는 번역된 텍스트를 복사하세요.
코드 분석
언어 데이터
const countries = { /*...*/ }
이 개체에는 사용 가능한 언어와 해당 국가 코드가 포함되어 있습니다. 예를 들어 "en-GB": "English"는 언어 코드와 이름을 연결합니다.
동적 드롭다운
selectTag.forEach((tag, id) => { /*...*/ });
이 코드는 국가 개체에 나열된 모든 언어로 드롭다운 메뉴를 동적으로 채웁니다. 첫 번째 드롭다운은 기본적으로 영어("en-GB")이고 두 번째 드롭다운은 힌디어("hi-IN")입니다.
언어 교환
exchageIcon.addEventListener("click", () => { /*...*/ });
교체 아이콘을 클릭하면 사용자가 "시작" 필드와 "끝" 필드 사이에서 텍스트와 선택한 언어를 바꿀 수 있습니다.
실시간 번역
translateBtn.addEventListener("click", () => { /*...*/ });
'번역' 버튼을 클릭하면 텍스트가 MyMemory API로 전송되고 번역된 텍스트가 'to-text' 필드에 표시됩니다. 응답을 기다리는 동안 "번역 중..." 자리 표시자가 표시됩니다.
텍스트 음성 변환 및 복사
icons.forEach(icon => { /*...*/ });
이 섹션에서는 텍스트 음성 변환 및 복사 기능을 다룹니다.
- 음성: 선택한 언어로 텍스트를 소리내어 재생합니다.
- 복사: 텍스트를 클립보드에 복사합니다.
작동 방식
- 언어 선택 ?: 드롭다운에서 언어를 선택하세요.
- 텍스트 입력 또는 붙여넣기 ✍️: 번역하려는 텍스트를 입력하세요.
- 번역 ?: "번역" 버튼을 클릭하고 마법이 일어나는 것을 지켜보세요!
- 교환, 듣기 또는 복사 ???: 언어를 교환하고, 번역을 듣거나 텍스트를 클립보드에 복사합니다.
종속성
- MyMemory API: 번역 기능은 MyMemory API를 통해 구동됩니다. 작동하려면 인터넷에 연결되어 있는지 확인하세요.
잠재적인 개선 사항
- 언어 자동 감지: 입력된 텍스트의 언어를 자동으로 감지합니다.
- 고급 오류 처리: 번역 오류 또는 API 오류에 대한 응답을 개선합니다.
- 다중 번역: 가능한 경우 대체 번역을 표시합니다.
코드 작동 방식과 기능에 대한 단계별 설명은 다음과 같습니다.
Step 1: Defining Available Languages
const countries = { /*...*/ }
- What it does: This object contains key-value pairs where the key is a language-country code (like "en-GB" for English) and the value is the name of the language (like "English").
- Purpose: This data is used to populate the language selection dropdowns so users can choose their source and target languages.
Step 2: Selecting DOM Elements
const fromText = document.querySelector(".from-text"), toText = document.querySelector(".to-text"), exchageIcon = document.querySelector(".exchange"), selectTag = document.querySelectorAll("select"), icons = document.querySelectorAll(".row i"); translateBtn = document.querySelector("button"),
-
What it does: This code selects various elements from the HTML document and stores them in variables for easy access later.
- fromText and toText: Text areas where users input text and see the translation.
- exchageIcon: The icon used to swap languages and text.
- selectTag: The dropdown menus for selecting languages.
- icons: Icons for copy and speech functions.
- translateBtn: The button that triggers the translation.
Step 3: Populating Language Dropdowns
selectTag.forEach((tag, id) => { for (let country_code in countries) { let selected = id == 0 ? country_code == "en-GB" ? "selected" : "" : country_code == "hi-IN" ? "selected" : ""; let option = `<option value="${country_code}">${countries[country_code]}</option>`; tag.insertAdjacentHTML("beforeend", option); } });
-
What it does: This loop goes through the countries object and adds each language as an option in the language selection dropdowns.
- If the dropdown is the first one (id == 0), English ("en-GB") is selected by default.
- If the dropdown is the second one (id == 1), Hindi ("hi-IN") is selected by default.
Step 4: Swapping Languages and Text
exchageIcon.addEventListener("click", () => { let tempText = fromText.value, tempLang = selectTag[0].value; fromText.value = toText.value; toText.value = tempText; selectTag[0].value = selectTag[1].value; selectTag[1].value = tempLang; });
-
What it does: When the swap icon is clicked, this function swaps the text between the "from" and "to" text areas as well as the selected languages.
- tempText temporarily holds the original text from the "from-text" field.
- tempLang temporarily holds the original language from the first dropdown.
- The "from-text" is then replaced with the "to-text", and vice versa. The selected languages are also swapped.
Step 5: Clearing Translated Text
fromText.addEventListener("keyup", () => { if(!fromText.value) { toText.value = ""; } });
- What it does: If the user deletes all the text from the "from-text" field, this function automatically clears the "to-text" field as well.
- Purpose: Ensures that if the input text is cleared, the translation is cleared too, preventing confusion.
Step 6: Translating Text
translateBtn.addEventListener("click", () => { let text = fromText.value.trim(), translateFrom = selectTag[0].value, translateTo = selectTag[1].value; if(!text) return; toText.setAttribute("placeholder", "Translating..."); let apiUrl = `https://api.mymemory.translated.net/get?q=${text}&langpair=${translateFrom}|${translateTo}`; fetch(apiUrl).then(res => res.json()).then(data => { toText.value = data.responseData.translatedText; data.matches.forEach(data => { if(data.id === 0) { toText.value = data.translation; } }); toText.setAttribute("placeholder", "Translation"); }); });
-
What it does: When the "Translate" button is clicked, this function:
- Extracts the text from the "from-text" field.
- Identifies the selected languages from the dropdowns.
- Sends a request to the MyMemory API with the text and selected languages.
- Receives the translation from the API and displays it in the "to-text" field.
- Updates the placeholder text while waiting for the translation to indicate that the process is ongoing.
Summary
The script allows users to translate text between different languages with a dynamic and interactive interface. Users can select languages, type in their text, translate it with a click, swap languages and text, hear the translation spoken aloud, or copy it to their clipboard.
Enjoy playing with different languages and make your translation journey fun and interactive! ?? Unto the next ?✌?✨
Check it out here
https://app.marvelly.com.ng/100daysofMiva/day-8/
Source code
https://github.com/Marvellye/100daysofMiva/blob/main/Projects%2FDay_8-Simple_language_translator
위 내용은 API를 사용한 간단한 언어 번역기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

실제 세계에서 JavaScript의 응용 프로그램에는 서버 측 프로그래밍, 모바일 애플리케이션 개발 및 사물 인터넷 제어가 포함됩니다. 1. 서버 측 프로그래밍은 Node.js를 통해 실현되며 동시 요청 처리에 적합합니다. 2. 모바일 애플리케이션 개발은 재교육을 통해 수행되며 크로스 플랫폼 배포를 지원합니다. 3. Johnny-Five 라이브러리를 통한 IoT 장치 제어에 사용되며 하드웨어 상호 작용에 적합합니다.

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.

이 기사에서는 Contrim에 의해 확보 된 백엔드와의 프론트 엔드 통합을 보여 주며 Next.js를 사용하여 기능적인 Edtech SaaS 응용 프로그램을 구축합니다. Frontend는 UI 가시성을 제어하기 위해 사용자 권한을 가져오고 API가 역할 기반을 준수하도록합니다.

JavaScript는 현대 웹 개발의 핵심 언어이며 다양성과 유연성에 널리 사용됩니다. 1) 프론트 엔드 개발 : DOM 운영 및 최신 프레임 워크 (예 : React, Vue.js, Angular)를 통해 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축합니다. 2) 서버 측 개발 : Node.js는 비 차단 I/O 모델을 사용하여 높은 동시성 및 실시간 응용 프로그램을 처리합니다. 3) 모바일 및 데스크탑 애플리케이션 개발 : 크로스 플랫폼 개발은 개발 효율을 향상시키기 위해 반응 및 전자를 통해 실현됩니다.

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

Python은 데이터 과학 및 기계 학습에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명하며 데이터 분석 및 웹 개발에 적합합니다. 2. JavaScript는 프론트 엔드 개발의 핵심입니다. Node.js는 서버 측 프로그래밍을 지원하며 풀 스택 개발에 적합합니다.

JavaScript는 이미 최신 브라우저에 내장되어 있기 때문에 설치가 필요하지 않습니다. 시작하려면 텍스트 편집기와 브라우저 만 있으면됩니다. 1) 브라우저 환경에서 태그를 통해 HTML 파일을 포함하여 실행하십시오. 2) Node.js 환경에서 Node.js를 다운로드하고 설치 한 후 명령 줄을 통해 JavaScript 파일을 실행하십시오.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

WebStorm Mac 버전
유용한 JavaScript 개발 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기
