日期对象
1 创建日期对象
const date = new Date()
console.log(date.getFullYear()) // 2023 完整年份
console.log(date.getMonth()) // 0-11 0表示1月
console.log(date.getDate()) // 日
console.log(date.getHours()) // 时
console.log(date.getMinutes()) // 分
console.log(date.getSeconds()) // 秒
date.setFullYear(2025)
console.log(date.getFullYear())
function getTime() {
const date = new Date()
const y = date.getFullYear()
const month = date.getMonth()
const d = date.getDate()
const h = date.getHours()
const m = date.getMinutes()
const s = date.getSeconds()
return `${y}-${month}-${d} ${h}:${m}:${s}`
}
创建一个自定义日期时间
const d = new Date(2024, 0, 1)
console.log(d.getFullYear())
console.log(d.getMonth())
console.log(d.getDate())
console.log(d.getTime()) // 时间戳,1970年1月1日到当前时间经历的豪秒数
const d2 = new Date()
console.log(d2.getTime())
console.log(+new Date()) // 时间戳
console.log(Date.now()) //;
倒计时案例
距离2024年1月1日 还剩多少天?多少时?多少分?多少秒
const targetTime = new Date('2024-1-1')
const date = new Date()
// 获取当前时间到目标时间的毫秒数
const diff = targetTime.getTime() - date.getTime()
console.log(diff)
// 24*3600*1000
const days = Math.floor(diff / (24 * 3600 * 1000))
console.log(days)
const hours = Math.floor((diff % (24 * 3600 * 1000)) / (3600 * 1000))
console.log(hours)
const minutes = Math.floor((diff % (3600 * 1000)) / (60 * 1000))
console.log(minutes)
const s = Math.floor((diff % (60 * 1000)) / 1000)
console.log(s)
document.write(`
距离2024年1月1日 还剩${days}天${hours}时${minutes}分${s}秒
`)
随机点名案例
// 声明一个数组
let arr = ["老赵", "老李", "小传", "小黑"]
// 生成1个随机数 作为数组的索引号
let random = Math.floor(Math.random()* arr.length)
document.write(arr[random])
数据类型比较
基本数据类型 与 引用数据类型
基本数据类型传的值本身,相当于把值复制一份
let num = 10
function f(num) {
num++
console.log(num)
}
f(num) //基本类型传的值本身,相当于把值复制一份
console.log(num) // 10
引用数据类型传的地址
let obj = { num: 10 } // obj存储该对象的地址
function f(obj) {
obj.num++
}
f(obj) // 引用类型传的地址
console.log(obj.num)
字符串方法
String.prototype.charAt()
String 的 charAt()
方法返回一个由给定索引处的单个 UTF-16 码元构成的新字符串。
示例
下例输出字符串 "Brave new world"
不同位置处的字符:
const anyString = "Brave new world";
console.log(`在索引 0 处的字符为 '${anyString.charAt()}'`);
// 没有提供索引,使用 0 作为默认值
console.log(`在索引 0 处的字符为 '${anyString.charAt(0)}'`);
console.log(`在索引 1 处的字符为 '${anyString.charAt(1)}'`);
console.log(`在索引 2 处的字符为 '${anyString.charAt(2)}'`);
console.log(`在索引 3 处的字符为 '${anyString.charAt(3)}'`);
console.log(`在索引 4 处的字符为 '${anyString.charAt(4)}'`);
console.log(`在索引 999 处的字符为 '${anyString.charAt(999)}'`);
上面代码的输出为:
在索引 0 处的字符为 'B'
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
console.log(
`Character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(
index,
)}`,
);
// Expected output: "Character code 113 is equal to q"
在索引 0 处的字符为 'B' 在索引 1 处的字符为 'r' 在索引 2 处的字符为 'a' 在索引 3 处的字符为 'v' 在索引 4 处的字符为 'e' 在索引 999 处的字符为 ''
String.prototype.charCodeAt()
String 的 charCodeAt()
方法返回一个整数,表示给定索引处的 UTF-16 码元,其值介于 0
和 65535
之间
示例
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
console.log(
`Character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(
index,
)}`,
);
// Expected output: "Character code 113 is equal to q"
String.prototype.concat()
concat()
方法将字符串参数连接到调用的字符串,并返回一个新的字符串。
const str1 = 'Hello';
const str2 = 'World';
console.log(str1.concat(' ', str2));
// Expected output: "Hello World"
console.log(str2.concat(', ', str1));
// Expected output: "World, Hello"
String.prototype.endsWith()
endsWith()
方法用于判断一个字符串是否以指定字符串结尾,如果是则返回 true
,否则返回 false
。
const str1 = 'Cats are the best!';
console.log(str1.endsWith('best!'));
// Expected output: true
console.log(str1.endsWith('best', 17));
// Expected output: true
const str2 = 'Is this a question?';
console.log(str2.endsWith('question'));
// Expected output: false
String.prototype.startsWith()
String 的 startsWith()
方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true
或 false
。
const str1 = 'Saturday night plans';
console.log(str1.startsWith('Sat'));
// Expected output: true
console.log(str1.startsWith('Sat', 3));
// Expected output: false
String.prototype.includes()
includes()
方法执行区分大小写的搜索,以确定是否可以在一个字符串中找到另一个字符串,并根据情况返回 true
或 false
。
const sentence = 'The quick brown fox jumps over the lazy dog.';
const word = 'fox';
console.log(
`The word "${word}" ${
sentence.includes(word) ? 'is' : 'is not'
} in the sentence`,
);
// Expected output: "The word "fox" is in the sentence"
String.prototype.indexOf()
String 的 indexOf()
方法在字符串中搜索指定子字符串,并返回其第一次出现的位置索引。它可以接受一个可选的参数指定搜索的起始位置,如果找到了指定的子字符串,则返回的位置索引大于或等于指定的数字。
const paragraph = "I think Ruth's dog is cuter than your dog!";
const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(`The index of the first "${searchTerm}" is ${indexOfFirst}`);
// Expected output: "The index of the first "dog" is 15"
console.log(
`The index of the second "${searchTerm}" is ${paragraph.indexOf(
searchTerm,
indexOfFirst + 1,
)}`,
);
// Expected output: "The index of the second "dog" is 38"
String.prototype.replace()
replace()
方法返回一个新字符串,其中一个、多个或所有匹配的 pattern
被替换为 replacement
。
const paragraph = "I think Ruth's dog is cuter than your dog!";
console.log(paragraph.replace("Ruth's", 'my'));
// Expected output: "I think my dog is cuter than your dog!"
const regex = /Dog/i;
console.log(paragraph.replace(regex, 'ferret'));
// Expected output: "I think Ruth's ferret is cuter than your dog!"
String.prototype.slice()
slice()
方法提取字符串的一部分,并将其作为新字符串返回,而不修改原始字符串。
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.slice(31));
// Expected output: "the lazy dog."
console.log(str.slice(4, 19));
// Expected output: "quick brown fox"
console.log(str.slice(-4));
// Expected output: "dog."
console.log(str.slice(-9, -5));
// Expected output: "lazy"
String.prototype.substring()
String 的 substring()
方法返回该字符串从起始索引到结束索引(不包括)的部分,如果未提供结束索引,则返回到字符串末尾的部分。
const str = 'Mozilla';
console.log(str.substring(1, 3));
// Expected output: "oz"
console.log(str.substring(2));
// Expected output: "zilla"
String.prototype.split()
split()
方法接受一个模式,通过搜索模式将字符串分割成一个有序的子串列表,将这些子串放入一个数组,并返回该数组。
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
console.log(words[3]);
// Expected output: "fox"
const chars = str.split('');
console.log(chars[8]);
// Expected output: "k"
const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]
String.prototype.trim()
String 的 trim()
方法会从字符串的两端移除空白字符,并返回一个新的字符串,而不会修改原始字符串。
const greeting = ' Hello world! ';
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trim());
// Expected output: "Hello world!";
String.prototype.toLowerCase()
String 的 toLowerCase()
方法将该字符串转换为小写形式。
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.toLowerCase());
// Expected output: "the quick brown fox jumps over the lazy dog."
String.prototype.toUpperCase()
String 的 toUpperCase()
方法将该字符串转换为大写形式。
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.toUpperCase());
// Expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."