欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 2025.4.21日学习笔记 JavaScript String、Array、date、math方法的使用

2025.4.21日学习笔记 JavaScript String、Array、date、math方法的使用

2025/4/23 18:23:42 来源:https://blog.csdn.net/2503_90593237/article/details/147402346  浏览:    关键词:2025.4.21日学习笔记 JavaScript String、Array、date、math方法的使用

1. String(字符串)

String 对象用于处理和操作文本数据。

  • length:返回字符串的长度。
const str = "Hello";
console.log(str.length); // 输出: 5
  • charAt(index):返回指定索引位置的字符。
const str = "Hello";
console.log(str.charAt(1)); // 输出: e
  • concat(str1, str2, ...):连接多个字符串。
const str1 = "Hello";
const str2 = " World";
console.log(str1.concat(str2)); // 输出: Hello World
  • toUpperCase() 和 toLowerCase():将字符串转换为大写或小写。
const str = "Hello";
console.log(str.toUpperCase()); // 输出: HELLO
console.log(str.toLowerCase()); // 输出: hello
  • indexOf(substring):返回子字符串在字符串中首次出现的位置,如果未找到则返回 -1。
const str = "Hello";
console.log(str.indexOf("l")); // 输出: 2

2. Array(数组)

Array 对象用于存储多个值,这些值可以是不同的数据类型。

  • push(item1, item2, ...):在数组末尾添加一个或多个元素,并返回新的长度。
const arr = [1, 2, 3];
const newLength = arr.push(4);
console.log(arr); // 输出: [1, 2, 3, 4]
console.log(newLength); // 输出: 4
  • pop():移除并返回数组的最后一个元素。
const arr = [1, 2, 3];
const lastElement = arr.pop();
console.log(arr); // 输出: [1, 2]
console.log(lastElement); // 输出: 3
  • splice(start, deleteCount, item1, item2, ...):从数组中添加或删除元素。
const arr = [1, 2, 3, 4];
arr.splice(1, 2, 5, 6);
console.log(arr); // 输出: [1, 5, 6, 4]
  • join(separator):将数组元素连接成一个字符串。
const arr = [1, 2, 3];
console.log(arr.join("-")); // 输出: 1-2-3
  • map(callback):创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
const arr = [1, 2, 3];
const newArr = arr.map(item => item * 2);
console.log(newArr); // 输出: [2, 4, 6]

3. Date(日期)

Date 对象用于处理日期和时间。

  • 创建日期对象
const now = new Date(); // 当前日期和时间
const specificDate = new Date("2025-04-21"); // 指定日期
  • getFullYear():返回年份。
const date = new Date();
console.log(date.getFullYear()); // 输出当前年份
  • getMonth():返回月份(0 - 11,0 表示一月)。
const date = new Date();
console.log(date.getMonth()); // 输出当前月份
  • getDate():返回日期(1 - 31)。
const date = new Date();
console.log(date.getDate()); // 输出当前日期
  • toLocaleString():将日期转换为本地字符串表示。
const date = new Date();
console.log(date.toLocaleString()); // 输出本地日期和时间字符串

4. Math(数学)

Math 是一个内置对象,它拥有一些数学常数和函数。

  • Math.PI:圆周率。
console.log(Math.PI); // 输出: 3.141592653589793
  • Math.random():返回一个介于 0(包含)和 1(不包含)之间的随机数。
console.log(Math.random()); // 输出一个随机数
  • Math.floor(x):返回小于或等于 x 的最大整数。
console.log(Math.floor(3.9)); // 输出: 3
  • Math.ceil(x):返回大于或等于 x 的最小整数。
console.log(Math.ceil(3.1)); // 输出: 4
  • Math.max(x1, x2, ...) 和 Math.min(x1, x2, ...):返回一组数中的最大值和最小值。
console.log(Math.max(1, 2, 3)); // 输出: 3
console.log(Math.min(1, 2, 3)); // 输出: 1

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词