一文掌握 React 开发中的 JavaScript 基础知识
前端开发中JavaScript是基石。在 React 开发中掌握掌握基础的 JavaScript 方法将有助于编写出更加高效、可维护的 React 应用程序。
在 React 开发中使用 ES6 语法可以带来更简洁、可读性更强、功能更丰富,以及更好性能和社区支持等诸多好处。这有助于提高开发效率,并构建出更加优秀的 React 应用程序。
原生JavaScript基础
- 数组方法:
// map()
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]// filter()
const words = ['apple', 'banana', 'cherry', 'date'];
const fruitsWithA = words.filter(word => word.includes('a'));
console.log(fruitsWithA); // ['apple', 'banana', 'date']// reduce()
const scores = [80, 85, 90, 92];
const totalScore = scores.reduce((acc, score) => acc + score, 0);
console.log(totalScore); // 347
- 字符串方法:
// split()/join()
const sentence = 'The quick brown fox jumps over the lazy dog.';
const words = sentence.split(' ');
console.log(words); // ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
const newSentence = words.join('-');
console.log(newSentence); // 'The-quick-brown-fox-jumps-over-the-lazy-dog.'// substring()/substr()
const longString = 'This is a long string with some information.';
const shortString = longString.substring(10, 20);
console.log(shortString); // 'long strin'
- 对象方法:
// Object.keys()/Object.values()/Object.entries()
const person = { name: 'John Doe', age: 30, email: 'john.doe@example.com' };
const keys = Object.keys(person);
console.log(keys); // ['name', 'age', 'email']
const values = Object.values(person);
console.log(values); // ['John Doe', 30, 'john.doe@example.com']
const entries = Object.entries(person);
console.log(entries); // [['name', 'John Doe'], ['age', 30], ['email', 'john.doe@example.com']]// Object.assign()
const base = { id: 1, name: 'John' };
const extended = Object.assign({}, base, { email: 'john@example.com' });
console.log(extended); // { id: 1, name: 'John', email: 'john@example.com' }
- 函数方法:
// call()/apply()
function greet(greeting, name) {console.log(`${greeting}, ${name}!`);
}greet.call(null, 'Hello', 'John'); // Hello, John!
greet.apply(null, ['Hi', 'Jane']); // Hi, Jane!// bind()
const boundGreet = greet.bind(null, 'Howdy');
boundGreet('Alice'); // Howdy, Alice!
- 其他常用方法:
// console.log()/console.error()
console.log('This is a log message');
console.error('This is an error message');// setTimeout()/setInterval()
setTimeout(() => {console.log('This message will be logged after 2 seconds');
}, 2000);let count = 0;
const interval = setInterval(() => {console.log(`This message will be logged every second. Count: ${count}`);count++;
}, 1000);// Clear the interval after 5 seconds
setTimeout(() => {clearInterval(interval);console.log('Interval cleared');
}, 5000);
在 React 开发中如使用基础的 JavaScript 方法
- 数组方法:
// map()
const items = ['item1', 'item2', 'item3'];
return (<ul>{items.map((item, index) => (<li key={index}>{item}</li>))}</ul>
);// filter()
const users = [{ id: 1, name: 'John', age: 30 },{ id: 2, name: 'Jane', age: 25 },{ id: 3, name: 'Bob', age: 40 }
];
const adults = users.filter(user => user.age >= 18);// reduce()
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15
- 字符串方法:
// split()/join()
const name = 'John Doe';
const nameParts = name.split(' ');
console.log(nameParts); // Output: ['John', 'Doe']
const formattedName = nameParts.join(', '); // 'Doe, John'// substring()/substr()
const longText = 'This is a long text with some information.';
const shortText = longText.substring(0, 10); // 'This is a '
- 对象方法:
// Object.keys()/Object.values()/Object.entries()
const user = { id: 1, name: 'John', email: 'john@example.com' };
const keys = Object.keys(user); // ['id', 'name', 'email']
const values = Object.values(user); // [1, 'John', 'john@example.com']
const entries = Object.entries(user); // [[id, 1], [name, 'John'], [email, 'john@example.com']]// Object.assign()
const baseProps = { id: 1, name: 'John' };
const extendedProps = { ...baseProps, email: 'john@example.com' };
- 函数方法:
// call()/apply()
class Button extends React.Component {handleClick = function(e) {console.log(this.props.label);}.bind(this);render() {return <button onClick={this.handleClick}>{this.props.label}</button>;}
}// bind()
class Button extends React.Component {constructor(props) {super(props);this.handleClick = this.handleClick.bind(this);}handleClick(e) {console.log(this.props.label);}render() {return <button onClick={this.handleClick}>{this.props.label}</button>;}
}
- 其他常用方法:
// console.log()/console.error()
console.log('This is a log message');
console.error('This is an error message');// setTimeout()/setInterval()
componentDidMount() {this.timer = setInterval(() => {this.setState(prevState => ({ count: prevState.count + 1 }));}, 1000);
}componentWillUnmount() {clearInterval(this.timer);
}
常用的 ES6 方法
- let/const:
let x = 5; // 块级作用域
const PI = 3.14159; // 不可重新赋值
- 箭头函数:
// 传统函数
const square = function(x) {return x * x;
};// 箭头函数
const square = (x) => {return x * x;
};// 简写
const square = x => x * x;
- 模板字面量:
const name = 'John';
const age = 30;
console.log(`My name is ${name} and I'm ${age} years old.`);
- 解构赋值:
const person = { name: 'John', age: 30, email: 'john@example.com' };
const { name, age } = person;
console.log(name, age); // 'John' 30const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest); // 1 2 [3, 4, 5]
- 类:
class Person {constructor(name, age) {this.name = name;this.age = age;}greet() {console.log(`Hello, my name is ${this.name}.`);}
}const john = new Person('John', 30);
john.greet(); // 'Hello, my name is John.'
- Promise:
const fetchData = () => {return new Promise((resolve, reject) => {// 模拟异步操作setTimeout(() => {resolve({ data: 'Hello, Promise!' });}, 2000);});
};fetchData().then(response => console.log(response.data)).catch(error => console.error(error));
- async/await:
const fetchData = async () => {try {const response = await fetchData();console.log(response.data);} catch (error) {console.error(error);}
};fetchData();
- Spread 运算符:
const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
const allNumbers = [...numbers1, ...numbers2];
console.log(allNumbers); // [1, 2, 3, 4, 5, 6]const person = { name: 'John', age: 30 };
const updatedPerson = { ...person, email: 'john@example.com' };
console.log(updatedPerson); // { name: 'John', age: 30, email: 'john@example.com' }
相关文章:

一文掌握 React 开发中的 JavaScript 基础知识
前端开发中JavaScript是基石。在 React 开发中掌握掌握基础的 JavaScript 方法将有助于编写出更加高效、可维护的 React 应用程序。 在 React 开发中使用 ES6 语法可以带来更简洁、可读性更强、功能更丰富,以及更好性能和社区支持等诸多好处。这有助于提高开发效率,并构建出更…...

读天才与算法:人脑与AI的数学思维笔记01_洛夫莱斯测试
1. 创造力 1.1. 创造力是一种原动力,它驱使人们产生新的、令人惊讶的、有价值的想法,并积极地将这些想法付诸实践 1.2. 创造出在表面上看似新的东西相对容易 1.3. 在遇到偶然间的创造性行为时,都会表现得异…...
嵌入式系统的时间保存问题,hwclock保存注意事项
几个要点 嵌入式板子要有RTC电路和钮扣电池。这个跟电脑主板一样。嵌入式系统要有相应的驱动。使用date设置时间 date -s "2024-04-11 10:33:26" 使用hwclock保存时间 嵌入式系统如何使用hwclock正确保存时间-CSDN博客...

jenkins(docker)安装及应用
jenkins Jenkins是一个开源的、提供友好操作界面的持续集成(CI)工具,起源于Hudson(Hudson是商用的),主要用于持续、自动的构建/测试软件项目、监控外部任务的运行(这个比较抽象,暂且写上,不做解…...
uni-app中,页面跳转前,进行拦截处理的方法
个人需求阐述: 当用户在页面A中,填写了内容之后,没有点击“保存/确定”,直接通过点击返回按钮或者手机的物理返回键直接返回时,需要给出一个二次确认的弹层,当用户点击确定离开之后,跳转到页面B…...

Jmeter参数化的 4 种方式用法总结
参数化就是用变量代替数据的过程,总结参数化的4种方式: 1、用户自定义变量 用户自定义变更有两种方法: (1)在测试计划面板中的用户定义的变量设置 说明:在此用户定义的变量对所有测试计划都会生效 &…...

华为OD机试 - 连续天数的最高利润额(Java 2024 C卷 100分)
华为OD机试 2024C卷题库疯狂收录中,刷题点这里 专栏导读 本专栏收录于《华为OD机试(JAVA)真题(A卷B卷C卷)》。 刷的越多,抽中的概率越大,每一题都有详细的答题思路、详细的代码注释、样例测试…...

C语言——内存函数的实现和模拟实现
1. memcpy 使用和模拟实现 void * memcpy ( void * destination, const void * source, size_t num ); 函数memcpy从source的位置开始向后复制num个字节的数据到destination指向的内存位置。 这个函数在遇到 \0 的时候并不会停下来。 如果source和destination有任何的重叠&am…...

如何优化邮箱Webhook API发送邮件的性能?
邮箱Webhook API发送邮件的流程?怎么用邮箱API发信? 高效、稳定的邮箱Webhook API发送邮件功能对于企业的日常运营至关重要。随着业务量的增长,如何优化邮箱Webhook API发送邮件的性能。AokSend将从多个方面探讨如何提升的效率。 邮箱Webho…...
OceanBase V4.X中常用的SQL(一)
整理了一些在OceanBase使用过程中常用的SQL语句,这些语句均适用于4.x版本,并将持续进行更新。后续还将分享一些V4.x版本常用的操作指南,以便更好地帮助大家使用OceanBase数据库。 集群信息 版本查看 show variables like version_comment; …...
代码随想录算法训练营第五十天|123.买卖股票的最佳时机III 188.买卖股票的最佳时机IV
123.买卖股票的最佳时机III 这道题一下子就难度上来了,关键在于至多买卖两次,这意味着可以买卖一次,可以买卖两次,也可以不买卖。 视频讲解:https://www.bilibili.com/video/BV1WG411K7AR https://programmercarl.com…...
Composer安装与配置:简化PHP依赖管理的利器(包括加速镜像设置)
在现代的PHP开发中,我们经常会使用许多第三方库和工具来构建强大的应用程序。然而,手动管理这些依赖项可能会变得复杂和耗时。为了解决这个问题,Composer应运而生。Composer是一个PHP的依赖管理工具,它可以帮助我们轻松地安装、更…...
灯塔:抽象类和接口笔记
什么是构造方法 构造方法是一种特殊的方法,它是一个与类同名且没有返回值类型的方法。 构造方法的功能主要是完成对象的初始化。当类实例化一个对象时会自动调用构造方法,且构造方法和其他方法一样也可以重载 继承抽象类需要实现所有的抽象方法吗 继…...
mybatis 入门
MyBatis是一款持久层框架,免除了几乎所有的JDBC代码、参数及获取结果集工作。可以通过简单的XML或注解来配置和映射原始类型、接口和Java POJO为数据库中的记录。 1 无框架下的JDBC操作 1)加载驱动:Class.forName(“com.mysql.cj.jdbc.Driv…...
Spring-AI-上下文记忆
引入依赖 pom文件 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.org/P…...

内存函数memcpy、mommove、memset、memcmp
目录 1、memcpy函数 memcpy函数的模拟实现 2、memmove函数 memmove函数的模拟实现 3、memset函数 4、memcmp函数 1、memcpy函数 描述: C 库函数 void *memcpy(void *str1, const void *str2, size_t n) 从存储区 str2 复制 n 个字节到存储区 str1。 声明&…...
symfony框架介绍
Symfony是一个功能强大的PHP框架,它提供了丰富的组件和工具来简化Web开发过程。以下是一些关于Symfony的主要特点: 可重用性: Symfony提供了一系列可重用的PHP组件,这些组件可以用于任何PHP应用程序中。灵活性: Symfony允许开发者根据项目需求灵活选择使用哪些组件,而不是强…...

【计算机毕业设计】游戏售卖网站——后附源码
🎉**欢迎来到琛哥的技术世界!**🎉 📘 博主小档案: 琛哥,一名来自世界500强的资深程序猿,毕业于国内知名985高校。 🔧 技术专长: 琛哥在深度学习任务中展现出卓越的能力&a…...

LabVIEW电信号傅里叶分解合成实验
LabVIEW电信号傅里叶分解合成实验 电信号的分析与处理在科研和工业领域中起着越来越重要的作用。系统以LabVIEW软件为基础,开发了一个集电信号的傅里叶分解、合成、频率响应及频谱分析功能于一体的虚拟仿真实验系统。系统不仅能够模拟实际电路实验箱的全部功能&…...

Docker 学习笔记(六):挑战容器数据卷技术一文通,实战多个 MySQL 数据同步,能懂会用,初学必备
一、前言 记录时间 [2024-4-11] 系列文章简摘: Docker学习笔记(二):在Linux中部署Docker(Centos7下安装docker、环境配置,以及镜像简单使用) Docker 学习笔记(三)&#x…...

高等数学(下)题型笔记(八)空间解析几何与向量代数
目录 0 前言 1 向量的点乘 1.1 基本公式 1.2 例题 2 向量的叉乘 2.1 基础知识 2.2 例题 3 空间平面方程 3.1 基础知识 3.2 例题 4 空间直线方程 4.1 基础知识 4.2 例题 5 旋转曲面及其方程 5.1 基础知识 5.2 例题 6 空间曲面的法线与切平面 6.1 基础知识 6.2…...
MySQL中【正则表达式】用法
MySQL 中正则表达式通过 REGEXP 或 RLIKE 操作符实现(两者等价),用于在 WHERE 子句中进行复杂的字符串模式匹配。以下是核心用法和示例: 一、基础语法 SELECT column_name FROM table_name WHERE column_name REGEXP pattern; …...
3403. 从盒子中找出字典序最大的字符串 I
3403. 从盒子中找出字典序最大的字符串 I 题目链接:3403. 从盒子中找出字典序最大的字符串 I 代码如下: class Solution { public:string answerString(string word, int numFriends) {if (numFriends 1) {return word;}string res;for (int i 0;i &…...

RNN避坑指南:从数学推导到LSTM/GRU工业级部署实战流程
本文较长,建议点赞收藏,以免遗失。更多AI大模型应用开发学习视频及资料,尽在聚客AI学院。 本文全面剖析RNN核心原理,深入讲解梯度消失/爆炸问题,并通过LSTM/GRU结构实现解决方案,提供时间序列预测和文本生成…...
Caliper 配置文件解析:fisco-bcos.json
config.yaml 文件 config.yaml 是 Caliper 的主配置文件,通常包含以下内容: test:name: fisco-bcos-test # 测试名称description: Performance test of FISCO-BCOS # 测试描述workers:type: local # 工作进程类型number: 5 # 工作进程数量monitor:type: - docker- pro…...
学习一下用鸿蒙DevEco Studio HarmonyOS5实现百度地图
在鸿蒙(HarmonyOS5)中集成百度地图,可以通过以下步骤和技术方案实现。结合鸿蒙的分布式能力和百度地图的API,可以构建跨设备的定位、导航和地图展示功能。 1. 鸿蒙环境准备 开发工具:下载安装 De…...

《Docker》架构
文章目录 架构模式单机架构应用数据分离架构应用服务器集群架构读写分离/主从分离架构冷热分离架构垂直分库架构微服务架构容器编排架构什么是容器,docker,镜像,k8s 架构模式 单机架构 单机架构其实就是应用服务器和单机服务器都部署在同一…...
书籍“之“字形打印矩阵(8)0609
题目 给定一个矩阵matrix,按照"之"字形的方式打印这个矩阵,例如: 1 2 3 4 5 6 7 8 9 10 11 12 ”之“字形打印的结果为:1,…...
前端工具库lodash与lodash-es区别详解
lodash 和 lodash-es 是同一工具库的两个不同版本,核心功能完全一致,主要区别在于模块化格式和优化方式,适合不同的开发环境。以下是详细对比: 1. 模块化格式 lodash 使用 CommonJS 模块格式(require/module.exports&a…...
深入解析 ReentrantLock:原理、公平锁与非公平锁的较量
ReentrantLock 是 Java 中 java.util.concurrent.locks 包下的一个重要类,用于实现线程同步,支持可重入性,并且可以选择公平锁或非公平锁的实现方式。下面将详细介绍 ReentrantLock 的实现原理以及公平锁和非公平锁的区别。 ReentrantLock 实现原理 基本架构 ReentrantLo…...