首页 > 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学习者快速成长!