본문 바로가기

나의 FE피봇이야기/Javascript

(63)
[ JS ] !! // ??문법 삼항 함수같은거 좀 보는데, !! ?? 이런 문법은 거의 못봐서. 검색해 봤어요. ?? - Nullish Coalescing Operator (널 병합 연산자)??는 왼쪽의 값이 null이나 undefined일 경우에만 오른쪽 값을 반환합니다. let name = null;let defaultName = "Anonymous";console.log(name ?? defaultName); // "Anonymous" 차이점:|| 연산자와 유사하지만, null이나 undefined인 경우에만 오른쪽 값을 반환합니다.||는 0, false, ""(빈 문자열)과 같은 falsy 값도 오른쪽 값을 반환할 수 있습니다. !! - Double Negation (이중 부정)여기서 "hello"는 truthy 값이므로 !!..
[ JS ] 컴퓨터가 생각하는 방식과 내가 생각하는 방식 차이(feat. 몇박 주무시나요?) 숙박 사이트를 만들어 보고 있다.  '숙박은 당연히 몇박을 잘꺼니' 가 전제로 필요하다. 컴퓨터와 나의 사고방식의 차이를 느꼈다. 나 : 어떻게 계산할까? 해서 년도, 월, 일 을 직접 빼줘야 한다고 생각했다.컴퓨터 : AI에게 물어보니 그건 ms 으로 바꾼다음에 계산한다.
[JS] JSON.stringify and JSON.parse 차이 둘을 먼저 구번 하기위해서 자바스크립트 JSON과 객체의 차이JSON 객체와 일반 JavaScript 객체(객체 리터럴이라고도 합니다)의 주요 차이점은 따옴표입니다 JSON(JavaScript Object Notation)은 문자열JSON 객체의 모든 키(key)와 문자열 유형 값은 큰따옴표(")로 감싸야 합니다.{   "name": "Jane Doe",   "favorite-game": "Stardew Valley",  "subscriber": false} JavaScript 객체객체 리터럴을 사용하면 키와 문자열을 큰따옴표로 묶을 필요가 없습니다. 단 객체 리터럴 문법에서는 대시(-)로 구분된 키는 따옴표로 감싸야 함. 따옴표를 사용하지 않으려면 키를 마켈표기법인 favoriteGames or fac..
[JS/Type] interface and type 타입스크립트 공식문서에 차이는 아래와 같다고 한다. the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable.타입은 새로운 속성을 추가하기 위해 유형을 다시 열 수 없는 반면, 인터페이스는 항상 확장할 수 있다는 점이 가장 큰 차이점입니다.출처https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces  interfacetypeproperty 추가 O O동일 명칭 사용 가능 OX interface Bear ..
[JS] return new Response 본 글은 무료 Gemini를 통해서 작성된 자료입니다.보통 뒷단에서 쓰는 것으로 예상새 응답 개체를 생성하여 호출자에게 다시 보내기 전에 속성 및 본문 콘텐츠(data.status or header etc)를 사용자 지정할 수 있습니다.클라이언트에 보내기 전에 응답 데이터나 헤더를 조작해야 할 때 유용. fetch('/data')   .then(response => {     if (!response.ok) {       return new Response('Error fetching data', { status: 500, statusText: 'Internal Server Error' }); }       return response.clone(); // Create a copy of the origi..
[JS/Type] 더 명확한 작성법 함수 작성법 function createCourse(): { name: string; isPaid: boolean } { ... }function createCourse(): { name: string; isPaid: boolean } { ... }Return TypeInferred from the object parameterExplicitly defined after a colonType SafetyLess strict, potential for runtime errorsStricter, compiler checks for correct return typeReadabilityLess clear about the return typeClearer, self-documenting with explicit retur..
[JS/Type] void (update : 2024.04) void : 결과 값을 반환하지 않는 함수함수 : void, never, [ ]never : 반환값(return) 정의 가능.(다만, 일반적인 정의 아님) => ex) throw Error(message);- 확인 하기 어려운 값 + 함수가 예외 or 프로그램을 종료한다는 뜻The never type represents values which are never observed. In a return type, this means that the function throws an exception or terminates execution of the program.never also appears when TypeScript determines there’s nothing left in a union. ..
[JS] How Promise works 이 자료는 아래의 블로그에서 가져온 정보입니다. https://lydiahallie.framer.website/blog/promise-execution Promise의 Process a new promis object is created in memory. the promis object contains some internal slots( [[PromiseState]], [[PrmiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] [[PromiseFulfillReactions]], [[PromiseRejectReactions]] These fields contain something calle..
[Javascript/Json] Json 데이터를 만들기 위한 크롤링 최근에 누군가가 콘솔에 스크립트를 써, 정보를 추출하는 것을 보고 나도 따라해 봤다. json 데이터 만들려고 코드 작성(ai+코드 좀 수정)유용하다. 이렇게 간단한 데이터를 추출해 봤다. // Select all product tiles var productTiles = document.querySelectorAll('.product-tile'); // Iterate over each product tile productTiles.forEach(function(tile) { // Get the title var title = tile.querySelector('.tile-body .pdp-link').textContent; // Get the image URL var imageUrl = tile.que..
[Js/format ] 날짜, 통화 데이터 등의 정보를 변환해주는 함수 통화(ts)const CURRENCY_FORMATTER = new Intl.NumberFormat(undefined, { currency : "ko", style:"currency",})export const formatCurrency = (number : number) =>{ return CURRENCY_FORMATTER.format(number)} 출처 : 직접 날짜예를 들어, 현재 날짜를 한국 사용자들을 위한 형식으로 변환하고 싶다면 DateTimeFormat() 생성자로 포맷터를 생성한 객체의 format() 함수를 호출하면 됩니다.> const koDtf = new Intl.DateTimeFormat("ko", { dateStyle: "long" });undefined> koDtf.format(..
[Javascript] function and ( ) =>{ } 비교 연습해보기 onClick 조회 () => { } 조회
[Javascript] fetch with post post를 쓸 때는 body에 데이터를 담아서 보내줘야 한다. 다만 여기서 주의해야 할 사항은 JSON.stringify()를 해줘야 한다는 것이다. 물론 여기에 맞춰야 할 양식이 있다. 나는 아직 이 부분이 미숙지 된 것 같다. 따라서 여기서 한번 정리해 놓고 가끔식 봐줘야 할꺼 같다. const options = { method : "POST", headers : { "Content-Type" : "application/json", // 아이디와 키값을 넣을 때도 있으니 연속해서 쓰는 방법도 숙지가 필요하다. 형태는 위에 동일하다. "API 명칭" : "API KEY" body : JSON.stringify({ word : keyword //사용자 페이지에서 전달 받은 값, content : 'inf..
[JavaScirpt] API URLSearchParams( url.searchParams.set ) 이 method는 순수자바스트크립트에서도 사용이 가능하며, 고로 react에서도 사용 가능. const naverUrl = new URL('https://openapi.naver.com/v1/search/book.json'); // Set 'query' parameter naverUrl.searchParams.set('query', 'your_search_term'); // Set additional parameters as needed naverUrl.searchParams.set('start', 1); // First page of results naverUrl.searchParams.set('display', 10); // Number of results per page console.log(nav..
[JavaScript]ScrollY? versus pageYoffset? 브라우저 반영 때문에 차이 발생 결론은 구형 브라우저 신경안써도 되면 scrollY 쓰고, 구형 브라우저까지 신경써야 한다면 pageYoffset을 쓴다.아니면 조건문 걸어서 둘 다 쓰던지. 참조 https://studyhardgogo.tistory.com/186
[React] 간단한 서버 세팅 하는 법 이 자료는 라매개발자 영상을 참조한 자료입니다. https://www.youtube.com/watch?v=d6suykcsNeY express를 통한 서버 설치. 서버용 폴더와 클라이언트용 폴더 각각 만들기 서버 설치 express를 이용한 서버 설치 1. (cmd) cd를 이용해 server 폴더 이동 2. (cmd 명령어) npm init 설치 3. (cmd 명령어) npm i express 4. 서버 파일 만들기 app.js // app.js 파일 안에 아래 code 넣기 const express = require('express') const app = express() app.get('/', function (req, res) { res.send('Hello World') }) app.listen..
[Javascript] vue.js computed와 methods computed 속성과 methods 속성의 차이점 computed => {{ }} methods = > attribute 1) {{ }}에 작성할 로직이 복잡하면 함수의 return 정의하여 사용(값 바로 >> {{ }} 전달 2) 계산량이 많아 캐시가 필요 1) 이벤트 핸들러 조정 가능 v-on 2) event가 발생 할 때 function () 작동 - 변수를 넣을 수 없음. - 변수를 넣을 수 있음. data : 단순한 값 computed : data의 단순한 값에 상태 변환( 사칙 연산 등) 정도면 사용 methods : prameter와 같은 값을 전달 받을 때 사용 methods > computed(사칙연산 등)) > data(메모리 할당 여부에 따라서 갈리는 듯) Computed compu..
[Javascript] scope 범위 (EnvironmentRecord / LexicalEnvironment) 이 내용은 책 '코어 자바스크립트'를 보고 저의 개인적인 해석으로 작성된 내용입니다. 내용이 틀릴 수도 있으니 중의 하시기 바랍니다. 실행 콘텍스트 - 실행 콘텍스트는 실행할 코드에 제공할 환경 정보들을 모아놓은 객체. - 실행 컨텍스트 객체는 활성화 되는 시점에 variableEnviroment, LexicalEnvironment, ThisBinding 세 가지 정보 수집. 실행 콘텍스트를 생성할 때 VariableEnvironment와 LexicalEnvironment가 동일한 내용으로 구성. LexicalEnvironment는 함수 실행 도중에 변경되는 사항이 즉시 반영되는 반면() VariableEnvironment는 초기 상태 유지. VariableEnvironment와 LexicalEnviro..
[Javascript] 위아래 정보값 찾기 Hierarchy: parentNode: The element's parent in the DOM tree. childNodes: A collection of all child nodes (elements, text nodes, comments). children: A collection of only child elements (not text nodes or comments). previousSibling and nextSibling: References to siblings in the DOM.
[Node.js] Node.js를 테스트 자료는 조코딩 영상을 참조하였습니다. node express(framework) - 웹 프레임워크(request response)를 만들고 사용하는 것 ( 단 node 자체 내장함스로도 서버 설정이 가능합니다.) express module 1. npm 'express'검색 2. (설치)cmd에서 'npm i express' 3. (실행) cmd에서 'node index.js' => 자기서버 'localhost:3000' port: 한 서버에 여러개의 포트 가능 FTP : 20,21(TCP) SSH : 22(TCP) 텔넷 : 23(TCP) SMTP : 25(TCP) DNS : 53(TCP/UDP) DHCP :67(TCP) HTTP : 80(TCP) HTTPS : 443(TCP) ap..
[CSS & Javascript]var 값 설정해서 JS에서 변경하기 var(--_원하는 명칭) 자바스크립트에서 명칭을 선택하고 원하는 값으로 변경 가능. 예시1) 예시 2)