자바스크립트 코드 조각

WBOY
풀어 주다: 2024-08-30 21:00:10
원래의
323명이 탐색했습니다.

Javascript Code Snippets

데이터 유형

기본 데이터 유형

숫자

let age = 25; 
로그인 후 복사

문자열

let name = "John";
로그인 후 복사

부울

let isStudent = true;
로그인 후 복사

정의되지 않음:

let address;
로그인 후 복사

무효

let salary = null;
로그인 후 복사

기호

let sym = Symbol("id");
로그인 후 복사

빅인트

let bigIntNumber = 1234567890123456789012345678901234567890n;
로그인 후 복사

NaN(Not-a-Number)
NaN은 "Not-a-Number"의 약자로 합법적인 숫자가 아닌 값을 나타냅니다

console.log(0 / 0); // NaN
console.log(parseInt("abc")); // NaN
로그인 후 복사

데이터 유형을 확인하는 방법은 무엇입니까?

console.log(typeof a);
로그인 후 복사

수업

1) 클래스는 생성자를 하나만 가질 수 있습니다

class gfg {
    constructor(name, estd, rank) {
        this.n = name;
        this.e = estd;
        this.r = rank;
    }

    decreaserank() {
        this.r -= 1;
    }
}

const test = new gfg("tom", 2009, 43);

test.decreaserank();

console.log(test.r);
console.log(test);
로그인 후 복사

계승

class car {
    constructor(brand) {
        this.carname = brand;
    }

    present() {
        return 'I have a ' + this.carname;
    }
}
class Model extends car {
    constructor(brand, model) {
        super(brand);
        super.present();
        this.model = model;
    }

    show() {
        return this.present() + ', it is a ' + this.model;
    }
}
로그인 후 복사

가져오기 및 설정

class car {
    constructor(brand) {
        this.carname = brand;
    }

    // Getter method
    get cnam() {
        return "It is " + this.carname;  // Return a value
    }

    // Setter method
    set cnam(x) {
        this.carname = x;
    }
}

const mycar = new car("Ford");
console.log(mycar.cnam);
로그인 후 복사

즉시 호출되는 함수 표현(IIFE)

IIFE는 정의되자마자 실행되는 함수입니다

(function() {
    console.log("IIFE executed!");
})();
로그인 후 복사

고차 함수

고차 함수는 다른 함수를 인수로 사용하거나 결과로 함수를 반환하는 함수입니다

function higherOrderFunction(callback) {
    return callback();
}

function sayHello() {
    return "Hello!";
}

console.log(higherOrderFunction(sayHello)); // "Hello!"
로그인 후 복사

가변 섀도우닝

변수 섀도잉은 지역 변수가 외부 범위의 변수와 동일한 이름을 가질 때 발생합니다.
지역 변수는 자체 범위 내에서 외부 변수를 재정의하거나 숨깁니다.
외부 변수는 그대로 유지되며 로컬 범위 외부에서 액세스할 수 있습니다.

var name = "John";

function sayName() {
  console.log(name);
  var name = "Jane";
}

sayName();
로그인 후 복사

JavaScript에서 HTML 요소에 액세스하기

JavaScript에서 HTML 요소에 액세스하는 방법에는 여러 가지가 있습니다.

ID로 요소 선택:

document.getElementById("elementId");
로그인 후 복사

클래스 이름으로 요소 선택:

document.getElementsByClassName("className");
로그인 후 복사

태그 이름으로 요소 선택:

document.getElementsByTagName("tagName");
로그인 후 복사

CSS 선택기:

document.querySelector(".className");
document.querySelectorAll(".className");
로그인 후 복사

값으로 전달

function changeValue(x) {
  x = 10;
  console.log("Inside function:", x)
}

let num = 5;
changeValue(num);
로그인 후 복사

참조로 전달

function changeProperty(obj) {
  obj.name = "Alice";
  console.log("Inside function:", obj.name); // Output: Inside function: Alice
}

let person = { name: "Bob" };
changeProperty(person);
console.log("Outside function:", person.name); // Output: Outside function: Alice
로그인 후 복사

엄격한 사용

자바스크립트 엔진을 엄격 모드로 전환하여 일반적인 코딩 실수를 포착하고 더 많은 예외를 발생시킵니다.

"use strict";
x = 10; // Throws an error because x is not declared
로그인 후 복사

스프레드 연산자

0개 이상의 인수나 요소가 예상되는 위치에서 배열이나 문자열과 같은 반복 가능 항목을 확장할 수 있습니다

function sum(a, b, c) {
    return a + b + c;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // Output: 6
로그인 후 복사

인스턴스오브

연산자는 객체가 특정 클래스 또는 생성자 함수의 인스턴스인지 확인합니다.

class Animal {
  constructor(name) {
    this.name = name;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
}

const myDog = new Dog('Buddy', 'Golden Retriever');

console.log(myDog instanceof Dog);   // true
console.log(myDog instanceof Animal); // true
console.log(myDog instanceof Object); // true
console.log(myDog instanceof Array);  // false
로그인 후 복사

필터

이 메소드는 제공된 함수에 의해 구현된 테스트를 통과한 모든 요소로 새 배열을 생성합니다.

const numbers = [1, 2, 3, 4, 5, 6];

const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers); // [2, 4, 6]
로그인 후 복사

줄이다

이 메서드는 배열의 각 요소에 대해 감소 함수를 실행하여 단일 출력 값을 생성합니다.

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((sum, value) => sum + value, 0);
// sum = 0 initially

console.log(sum); // 15
로그인 후 복사

나머지

이 매개변수 구문을 사용하면 함수가 무한한 개수의 인수를 배열로 받아들일 수 있습니다.

function sum(...numbers) {
  return numbers.reduce((sum, value) => sum + value, 0);
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(5, 10, 15, 20)); // 50
로그인 후 복사

선언 유형

암시적 전역 변수
암시적 전역 변수는 var, let, const 등의 키워드를 사용하여 명시적으로 선언하지 않고 값을 할당하면 전역 범위에서 자동으로 생성되는 변수입니다. 하지만 엄격 모드
인 경우 오류가 발생합니다.

function myFunction() {
    x = 10; // no error
}
로그인 후 복사

상수
재할당할 수 없는 상수 변수를 선언합니다.

const PI = 3.14;
로그인 후 복사

하자
블록 범위 변수를 선언합니다.
동일한 이름으로 다시 초기화할 수 없습니다

let c=1;
let c=3;// throws error
let count = 0;
if (true) {
    let count = 1;
    console.log(count); // Output: 1
}
console.log(count); // Output: 0
로그인 후 복사

변수
함수 범위 또는 전역 범위 변수를 선언합니다. 끌어올리기와 재할당을 장려합니다.

var name = 'John';
if (true) {
    var name = 'Doe';
    console.log(name); // Output: Doe
}
console.log(name); // Output: Doe

console.log(a)
var a=2 // prints undefined
로그인 후 복사

합성 이벤트

합성 이벤트: React는 기본 브라우저 이벤트 주위에 SyntheticEvent 래퍼를 제공합니다. 이 래퍼는 다양한 브라우저에서 이벤트 속성과 동작을 정규화하여 이벤트 처리 코드가 브라우저에 관계없이 동일한 방식으로 작동하도록 보장합니다.

import React from 'react';

class MyComponent extends React.Component {
  handleClick = (event) => {
    // `event` is a SyntheticEvent
    console.log(event.type); // Always 'click' regardless of browser
    console.log(event.target); // Consistent target property
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}
로그인 후 복사

자바스크립트에서 호이스팅

호이스팅은 컴파일 단계에서 변수와 함수 선언이 포함 범위의 맨 위로 이동되어 코드에서 선언되기 전에 사용할 수 있도록 하는 JavaScript 메커니즘입니다. 그러나 초기화는 아닌 선언만 호이스팅됩니다.

console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5

// Function hoisting
hoistedFunction(); // Output: "Hoisted!"
function hoistedFunction() {
    console.log("Hoisted!");
}

// Function expressions are not hoisted
notHoisted(); // Error: notHoisted is not a function
var notHoisted = function() {
    console.log("Not hoisted");
};
로그인 후 복사

유형 강제

한 데이터 유형에서 다른 데이터 유형으로 값을 자동으로 변환하는 것입니다. 강제에는 암시적 강제와 명시적 강제의 두 가지 유형이 있습니다.

암묵적 강제

예.

let result = 5 + "10"; // "510"
let result = "5" * 2; // 10
let result = "5" - 2; // 3
let result = "5" / 2; // 2.5
로그인 후 복사

명시적 강제

내장 함수를 사용하여 값을 한 유형에서 다른 유형으로 수동으로 변환할 때 발생합니다.

let num = 5;
let str = String(num); // "5"
let str2 = num.toString(); // "5"
let str3 = `${num}`; // "5"
로그인 후 복사

Truthy Values

Non-zero numbers (positive and negative)
Non-empty strings
Objects (including arrays and functions)
Symbol
BigInt values (other than 0n)

Falsy Values

0 (zero)
-0 (negative zero)
0n (BigInt zero)
"" (empty string)
null
undefined
NaN (Not-a-Number)

Props (Properties)

To pass data from a parent component to a child component. It is immutable (read-only) within the child component.

// Parent Component
function Parent() {
  const data = "Hello from Parent!";
  return <Child message={data} />;
}

// Child Component
function Child(props) {
  return <div>{props.message}</div>;
}
로그인 후 복사

State

To manage data that can change over time within a component. It is mutable within the component.

// Function Component using useState
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
로그인 후 복사

Closure

A closure in JavaScript is a feature where an inner function has access to the outer (enclosing) function's variables and scope chain even after the outer function has finished executing.

function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log('Outer Variable:', outerVariable);
    console.log('Inner Variable:', innerVariable);
  };
}

const newFunction = outerFunction('outside');
newFunction('inside');
로그인 후 복사

Currying

Currying is a technique of transforming a function that takes multiple arguments into a sequence of functions that each take a single argument.

function add(a) {
  return function(b) {
    return a + b;
  };
}

const add5 = add(5);
console.log(add5(3)); // Output: 8
console.log(add(2)(3)); // Output: 5
로그인 후 복사

Generators

Generators are special functions that can be paused and resumed, allowing you to generate a sequence of values over time.

function* generateSequence() {
  yield 1;
  yield 2;
  yield 3;
}

const generator = generateSequence();

console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
로그인 후 복사

Stay Connected!
If you enjoyed this post, don’t forget to follow me on social media for more updates and insights:

Twitter: madhavganesan
Instagram: madhavganesan
LinkedIn: madhavganesan

위 내용은 자바스크립트 코드 조각의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!