首頁 > web前端 > js教程 > 主體

JavaScript 程式碼片段

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");
登入後複製

BigInt

let bigIntNumber = 1234567890123456789012345678901234567890n;
登入後複製

非數字 (NaN)
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
登入後複製

使用嚴格

它將 JavaScript 引擎切換到嚴格模式,捕捉常見的編碼錯誤並引發更多異常。

"use strict";
x = 10; // Throws an error because x is not declared
登入後複製

擴充運算符

它允許在需要零個或多個參數或元素的地方擴展可迭代對象,例如數組或字串

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
它聲明一個函數範圍或全域範圍的變數。它鼓勵提升和重新分配。

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 中的提升

提升是一種 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

以上是JavaScript 程式碼片段的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!