写在前面
以下的十二个小知识点,希望小伙伴们动手敲一敲有意想不到的收获
一、const
- const声明标量的时候,是不可以改变这个标量的值的。但是这里有一前提——在同一个作用域里面是不能改的。
- const在声明一个引用类型的数据时候,比如声明一个对象,是可以改变对象里面的数据的。 这里const改变的是数据的内存地址。
二、Object.freeze()冻结标量
看一个例子,我们定一个引用类型的数据
const HOST = {
url: "panderCode.com",
port: "8080"
}
这时候我们可以修改url和port的值的。
当我们定义完了以后,不允许被修改,我们就可以使用Object.freeze()冻结它.
Object.freeze(HOST);
这时候,我们就不能修改Host中的值。 我们可以使用 use strict; 如果修改了就让它报错。
三、理解标量与引用类型的传值和传址特性
**传值 **
我们先来看例子吧
let a = 1;
let b = a;
上面这个例子就是传值,我们话一个图了解一下
上面这幅图的意思是:
当声明a的时候,浏览器会给a一个内存地址。
当我们把a赋值给b的时候,浏览器会重新给b一个内存地址。当我们修改b的值的时候,就不会影响到a的值。
传址
再看一个例子:
let c = {value:"asd", key:"qwe"};
let d = c;
上面这个例子就是传址,当我们把c复制给d的时候,我们传的是内存地址,也就是说此时的d和c公用一个内存地址,当我们修改d的值,c的值也会改变。
我们再看一个图:
这就是传值和传址的区别
四、null和undefined的区别
在最开始js是没有undefined的,后面增加了undefined数据类型
- 我们在声明引用类型的时候,只是声明不赋值,当我们打印它,就会输出null
- 当我们声明基本类型的时候,只是声明不赋值,当我们打印它,就会 输出undefined
五、严格模式的作用范围
严格模式的作用范围是向下作用域的,这句话的意思是,你没有在全局作用域里面定义严格模式,那么严格模式就不会影响到全局,智慧影响到局部作用域中的内存。及其向下的作用域。
六、for in/ for of
- for in我们一般用作对象的遍历,遍历的输出是对象的键
- for of我们一般用作数组、字符串、dom节点的遍历,遍历的输出是值(value)
七、字符串中,常用的方法
let name = " leanSocket";
console.log(name.length); // 获取字符串长度
console.log(name.toUpperCase()); // 字符串字母转换成大写
console.log(name.toLowerCase()); // 字符串字母转换成小写
console.log(name.trim().length); // 去掉字符串前后空格
八、字符串截取
let hd = "LeanSocket.com";
console.log(hd.slice(1, 3)); // 第一个参数是截取的开始位置,第二个是结束位置
console.log(hd.substring(1, 3)) // 第一个参数是截取的开始位置,第二个是结束位置
console.log(hd.substr(1, 3)); // 第一个参数是截取的开始位置,第二个是截图的字符长度
console.log(hd.slice(-3, -1));
console.log(hd.substring(-3, -1));
console.log(hd.substr(-3, 2))
九、字符串查找
let hd = "LeanSocket.com";
if(hd.indexOf("l") !== -1) {
console.log("找到了!")
}
console.log(hd.includes("o", 2)) //第二个参数辨识从第几个开始查找
// 查找字符在哪个位置出现, 后面这个参数,是查找的前面几个数
console.log(hd.lastIndexOf("o", 9));
// 查找字符是不是在开始的位置出现
console.log(hd.startsWith("l"));
// 查找字符是不是在结束的位置出现
console.log(hd.endsWith("m"));
// 字符串匹配,就近匹配,如果第一个就匹配了就不会向后匹配了。
const word = ["react", "vue"];
const str = "我喜欢在b站学习react和vue的知识";
const status = word.some(word => {
return str.includes(word);
});
if(status) {
console.log("找到了")
}
十、字符串替换
let hd = "leanSocket.com";
console.log(hd.replace("leanSocket","zpw"))
const word = ["react", "vue"];
const str = "我喜欢在b站学习react和vue的知识";
const replaceString = word.reduce((pre, word)=>{
// 这个pre 第一次会接收str, 第二次就会返回我们return的内容
console.log(pre)
// 这里我们就可以把,react和vue加上超链接
return pre.replace(word, `<a href="?w=${word}">${word}</a>`);
}, str);
console.log(replaceString);
document.body.innerHTML += replaceString;
十一、电话号码模糊处理
function phone(mobile, len=3) {
return String(mobile).slice(0, len * -1) + "*".repeat(len)
}
console.log(phone(1383649468,5));
十二、类型转换
const str = "99";
console.log(typeof str);
console.log(str*1 + 88);
console.log(Number(str) + 88);
const num = 66;
console.log(typeof num);
const str = num + "";
console.log(typeof str);
console.log(typeof String(num));
const str = "99.78loadasdafasf";
console.log(parseInt(str));
console.log(parseFloat(str));