链接: https://houdunren.gitee.io/note/.
实际操作
基础知识
1. 在用户输入表单项并接收协议后才可提交
<form action="https://www.baidu.com" id="from">
用户名: <input type="text" name="username">
<hr>
<input type="checkbox" name="copyright">接受协议
<hr>
<input type="submit">
</form>
<script>
function query(el) {
return document.querySelector(el)
}
query("#from").addEventListener("submit", function (event) {
let username = query('input[name = "username"]').value
let checkbox = query('input[name = "copyright"]').checked
console.log(!!username)
if (!username || copyright === false) {
alert("请填写用户名并接受协议");
event.preventDefault();
}
})
</script>
2. 下面是使用多条件判断密码强度的示例
<input type="password" name="title" id="ip"> <span></span>
<script>
let input = document.getElementById('ip')
input.addEventListener('keyup', function () {
let length = this.value.length
let msg;
if (length > 10) {
msg = '你的密码太安全了'
} else if (length > 5) {
msg = '密码等级中等'
} else {
msg = '密码不安全'
}
document.querySelector("span").innerHTML = msg;
})
</script>
3. 使用循环制作杨辉三角的案例
<style>
span {
color: white;
}
</style>
<script>
function hd(row = 5) {
for (let i = 1; i < row; i++) {
for (let n = row - i; n > 0; n--) {
document.write('<span>*</span>')
}
for (let m = i * 2 - 1; m > 0; m--) {
document.write('*')
}
document.write('<br/>')
}
}
hd(16)
4. for/in遍历数组操作
let timo = [
{ title: "第一章 走进JAVASCRIPT黑洞", lesson: 3 },
{ title: "ubuntu19.10 配置好用的编程工作站", lesson: 5 },
{ title: "媒体查询响应式布局", lesson: 8 }
];
document.write(`
<table border="1" width="100%">
<thead><tr><th>标题</th><th>课程数</th></thead>
`);
for (let key in timo) {
document.write(`
<tr>
<td>${timo[key].title}</td>
<td>${timo[key].lesson}</td>
</tr>
`);
}
document.write("</table>");
5. for/in遍历对象操作
let info = {
name: "后盾人",
url: "houdunren.com"
};
for (const key in info) {
if (info.hasOwnProperty(key)) {
console.log(info[key]);
}
}
6. for/of遍历数组操作
用来遍历 Arrays(数组), Strings(字符串), Maps(映射), Sets(集合)等可迭代的数据结构。
与 for/in 不同的是 for/of 每次循环取其中的值而不是索引。
const ccc = ["hdcms", "houdunren"];
for (const [key, value] of ccc.entries()) {
console.log(key, value); //这样就可以遍历了
}
基本类型
1. 类型检测
- typeof 用于返回以下原始类型
基本类型:number/string/boolean
function / object / undefined
let a = 1;
console.log(typeof a); //number
let b = "1";
console.log(typeof b); //string
//未赋值或不存在的变量返回undefined
var hd;
console.log(typeof hd);
function run() {}
console.log(typeof run); //function
let c = [1, 2, 3];
console.log(typeof c); //object
let d = { name: "houdunren.com" };
console.log(typeof d); //object
- instanceof
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。 也可以理解为是否为某个对象的实例,typeof不能区分数组,但instanceof则可以。
let hd = [];
let houdunren = {};
console.log(hd instanceof Array); //true
console.log(houdunren instanceof Array); //false
let c = [1, 2, 3];
console.log(c instanceof Array); //true
let d = { name: "houdunren.com" };
console.log(d instanceof Object); //true
function User() {}
let hd = new User();
console.log(hd instanceof User); //true
- 值类型与对象
let hd = "houdunren";
let cms = new String("hdcms");
console.log(typeof hd, typeof cms); //string object
只有对象才有方法使用,但在JS中也可以使用值类型调用方法,因为它会在执行时将值类型转为对象。
let hd = "houdunren";
let cms = new String("hdcms");
console.log(hd.length); //9
console.log(cms.length); //5
2. String
- 声明定义
1.1 字符串使用单、双引号包裹,单、双引号使用结果没有区别。
let content = '后盾人';
console.log(content); //后盾人
1.2 使用对象形式创建字符串
let hd = new String('houdunren');
// 获取字符串长度
console.log(hd.length);
// 获取字符串
console.log(hd.toString());
- 转义符号
常用转义符号列表如下
符号 | 说明 |
---|---|
\t | 制表符 |
\n | 换行 |
\ | 斜杠符号 |
’ | 单引号 |
" | 双引号R |
- 连接运算符
使用 + 可以连接多个内容组合成字符串,经常用于组合输出内容使用。
let lessons = [
{title: '媒体查询响应式布局'},{title: 'FLEX 弹性盒模型'},{title: 'GRID 栅格系统'}
];
function template() {
return `<ul>
${lessons.map((item)=>`
<li>${item.title}</li>
`).join('')}
</ul>`;
}
document.body.innerHTML = template();
- 标签模板
标签模板是提取出普通字符串与变量,交由标签函数处理
let lesson = 'css';
let web = '后盾人';
tag `访问${web}学习${lesson}前端知识`;
function tag(strings, ...values) {
console.log(strings); //["访问", "学习", "前端知识"]
console.log(values); // ["后盾人", "css"]
}
将标题中有后盾人的使用标签模板加上链接
let lessons = [
{ title: "后盾人媒体查询响应式布局", author: "后盾人向军" },
{ title: "FLEX 弹性盒模型", author: "后盾人" },
{ title: "GRID 栅格系统后盾人教程", author: "古老师" }
];
function links(strings, ...vars) {
return strings
.map((str, key) => {
return (
str +
(vars[key]
? vars[key].replace(
"后盾人",
`<a href="https://www.houdunren.com">后盾人</a>`
)
: "")
);
})
.join("");
}
function template() {
return `<ul>
${lessons
.map(item => links`<li>${item.author}:${item.title}</li>`)
.join("")}
</ul>`;
}
document.body.innerHTML += template();
- 获取长度
console.log('xilin'.length)
- 大小写转换
console.log('houdunren.com'.toUpperCase()); //HOUDUNREN.COM
console.log('houdunren.com'.toLowerCase()); //houdunren.com
- 移除空白
//使用trim删除字符串左右的空白字符
let str = ' houdunren.com ';
console.log(str.length);
console.log(str.trim().length);
使用trimLeft删除左边空白,使用trimRight删除右边空白
let name = " houdunren ";
console.log(name);
console.log(name.trimLeft());
console.log(name.trimRight());
- 获取单字符
//根据从0开始的位置获取字符
console.log('houdunren'.charAt(3)) //d
//使用数字索引获取字符串
console.log('houdunren'[3]) //d
- 截取字符串
使用 slice、substr、substring 函数都可以截取字符串。
- slice、substring 第二个参数为截取的结束位置
- substr 第二个参数指定获取字符数量
let xl = 'xilinTom'
console.log(xl)
console.log(xl.slice(3))
console.log(xl.substr(4))
console.log(xl.substring(5))
console.log(xl.slice(2, 4))
console.log(xl.substring(3, 6)); //inT
console.log(xl.substring(3, 0)); //xil 较小的做为起始位置
console.log(xl.substr(3, 6)); //inTom
console.log(xl.slice(3, -1)); //inTo 第二个为负数表示从后面算的字符
console.log(xl.slice(-2));//om 从末尾取
console.log(xl.substring(3, -9)); //xil 负数转为0
console.log(xl.substr(-3, 2)); //To 从后面第三个开始取两个
- 查找字符串
从开始获取字符串位置,检测不到时返回 -1
console.log('houdunren.com'.indexOf('o')); //1
console.log('houdunren.com'.indexOf('o', 3)); //11 从第3个字符向后搜索
console.log('houdunren.com'.lastIndexOf('o')); //11
console.log('houdunren.com'.lastIndexOf('o', 7)); //1 从第7个字符向前搜索
let str = "houdunren.com";
console.log(str.search("com"));
console.log(str.search(/\.com/i));
查找关键词的示例
let word = ['js', 'css']
let title = '我爱学习 js 和css知识'
let status = word.some(word => {
return title.includes(word);
})
console.log(status)
- 替换字符串
let name = "houdunren.com";
web = name.replace("houdunren", "hdcms");
console.log(web);
使用字符串替换来生成关键词链接
//使用字符串替换来生成关键词链接
const word = ["php", "css"];
const string = "我喜欢在后盾人学习php与css知识";
const title = word.reduce((pre, word) => {
return pre.replace(word, `<a href="?w=${word}">${word}</a>`);
}, string);
document.body.innerHTML += title;
- 重复生成
模糊后电话号码
//模糊后电话号码
function phone(mobile,len = 11) {
console.log(mobile)
return String(mobile).slice(0,len*-1) + '*'.repeat(len)
}
console.log(phone(15774611712))
- 类型转换
// 分割字母
let name = 'xilin'
console.log(name.split(''))
// 1.将字符串转换为数组
let name = 'xilin'
console.log(name.split(','))
// 隐式类型转换会根据类型自动转换类型 数字=>字符串
let hd = 99 + '';
console.log(typeof hd); //string
// 使用 String 构造函数可以显示转换字符串类型
let hd = 99;
console.log(typeof String(hd));
// js中大部分类型都是对象,可以使用类方法 toString转化为字符串
let hd = 99;
console.log(typeof hd.toString()); //string
let arr = ['hdcms', '后盾人'];
console.log(typeof arr.toString()); //string
3.Boolean
布尔类型包括 true 与 false 两个值,开发中使用较多的数据类型。
- 使用 !! 转换布尔类型
- 使用 Boolean 函数可以显式转换为布尔类型
使用Boolean类型判断用户的输入,并给出不同的反馈。
while (true) {
const year = prompt('北京奥运会哪年?').trim()
if(!year) continue;
alert(year == 2008? '回答正确' : '回答错误')
break;
}
4. Number
- 基本函数
let num = 18.8
// 判断是否为整数
console.log(Number.isInteger(num)) //false
// 指定返回的小数位数可以四舍五入
console.log(num.toFixed()) //19
2.NaN
可以使用 Object.is 方法判断两个值是否完全相同
parseInt: 提取字符串开始去除空白后的数字转为整数。
parseFloat: 转换字符串为浮点数,忽略字符串前面空白字符。
var res = 2 / 'houdunren';
console.log(Object.is(res, NaN)); //true
console.log(parseInt(' 99houdunren')); //99
console.log(parseInt('18.55')); //18
console.log(parseFloat(' 99houdunren')); //99
console.log(parseFloat('18.55')); //18.55
console.log(1.556.toFixed(2)); //1.56
舍入操作: 使用 toFixed 可对数值舍入操作,参数指定保存的小数位
浮点精度:大部分编程语言在浮点数计算时都会有精度误差问题—处理方式
- 一种方式使用toFixed 方法进行小数截取
- 将小数转为整数进行计算后,再转为小数也可以解决精度问题
console.log((0.1 + 0.2).toFixed(2)) //0.3
console.log(1.0 - 0.9) //0.09999999999999998
console.log((1.0 - 0.9).toFixed(2)) //0.10
Number.prototype.add = function (num) {
//取两个数值中小数位最大的
let n1 = this.toString().split('.')[1].length
let n2 = num.toString().split('.')[1].length
//得到10的N次幂
let m = Math.pow(10, Math.max(n1, n2))
return (this * m + num * m) / m
}
console.log((0.1).add(0.2))
<script src="https://cdn.bootcss.com/decimal.js/10.2.0/decimal.min.js"></script>
<script>
console.log(Decimal.add(0.1, 0.2).valueOf())
</script>
Math
//使用 min 与 max 可以取得最小与最大值。
console.log(Math.min(1, 2, 3)); //1
console.log(Math.max(1, 2, 3)); //3
//使用apply 来从数组中取值
console.log(Math.max.apply(Math, [1, 2, 3])); //3
//取最接近的向上整数
console.log(Math.ceil(1.111)); //2
//得到最接近的向下整数
console.log(Math.floor(1.555)); //1
//四舍五入处理
console.log(Math.round(1.5)); //2
random 方法用于返回 >=0 且 <1 的随机数(包括0但不包括1)。
5.Date
网站中处理日期时间是很常用的功能
moment.js
Moment.js是一个轻量级的JavaScript时间库,它方便了日常开发中对时间的操作,提高了开发效率。
更多使用方法请访问中文官网 http://momentjs.cn 或 英文官网 https://momentjs.com
<script src="https://cdn.bootcss.com/moment.js/2.24.0/moment.min.js"></script>
//获取当前时间
console.log(moment().format("YYYY-MM-DD HH:mm:ss"));
//设置时间
console.log(moment("2020-02-18 09:22:15").format("YYYY-MM-DD HH:mm:ss"));