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