字符串的新增方法:
includes():
判断字符串中是否含有某些字符。
1、基本用法:
判断字符是不是在字符串中:
console.log('abc'.includes('a')); // true
console.log('abc'.includes('ab')); // true
console.log('abc'.includes('bc')); // true
console.log('abc'.includes('ac')); // false
2、第二个参数:
表示开始搜索的位置,默认是 0。
console.log('abc'.includes('a')); // true
console.log('abc'.includes('a', 0)); // false
console.log('abc'.includes('a', 1)); // false
padStart() 和 padEnd():
用来补全字符串长度。
1、基本用法:
padStart是从头部开始补全,padEnd是从尾部开始补全,有两个参数,第一个参数是补全后字符串的长度,第二个参数是补的内容。
console.log('x'.padStart(5, 'ab')); // ababx
console.log('x'.padEnd(5, 'ab')); // xabab
console.log('x'.padEnd(4, 'ab')); // xaba
2、注意事项:
原字符串的长度,等于或大于最大长度,不会消减原字符串,字符串补全不生效,返回原字符串。
console.log('xxx'.padStart(2, 'ab')); // xxx
console.log('xxx'.padEnd(2, 'ab')); // xxx
用来补全的字符串与原字符串长度之和超过了最大长度,截去超出位数的补全字符串,原字符串不动。
console.log('abc'.padStart(10, '0123456789')); // 0123456abc
console.log('abc'.padEnd(10, '0123456789')); // abc0123456
如果省略第二个参数,默认使用空格补全长度。
console.log('x'.padStart(4)); // x
console.log('x'.padEnd(4)); // x
3、应用:
显示日期格式:
在实际开发中为了显示日期格式一致,就可以用到padStart和padEnd
console.log('10'.padStart(2, 0)); // 10
console.log('1'.padStart(2, 0)); // 02
trimStart() 和 trimEnd():
清除字符串的首或尾空格,中间的空格不会清除。
1、基本用法:
trimStart()也叫trimLeft(),trimEnd()也叫trimRight(),trim()会直接将首位的空格去干净!还有这种方法是实例化的,不会改变原来变量的值!
const s = ' a b c ';
console.log(s); // a b c
console.log(s.trimStart()); // a b c
console.log(s.trimLeft()); // a b c
console.log(s.trimEnd()); // a b c
console.log(s.trimRight()); // a b c
console.log(s.trim()); // a b c
2、应用:
在实际开发中用的比较多,一般用到表单提交。
如果表单提交的是空格,前端应该筛选出来不传输给后端,这就起一个筛选作用:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>trimStart() 和 trimEnd()</title>
</head>
<body>
<input type="text" id="username" />
<input type="submit" value="提交" id="btn" />
<script>
const usernameInput = document.getElementById('username');
const btn = document.getElementById('btn');
btn.addEventListener(
'click',
() => {
console.log(usernameInput.value);
// 验证
console.log(usernameInput.value.trim());
if (usernameInput.value.trim() !== '') {
// 可以提交
console.log('可以提交');
} else {
// 不能提交
console.log('不能提交');
}
// 手动提交
},
false
);
</script>
</body>
</html>
数组的新增方法:
includes():
1、判断数组中是否含有某个成员。
console.log([1, 2, 3].includes('2')); // false
console.log([1, 2, 3].includes(2)); // true
第一个错误的原因是 ‘2’ 是字符串 , 2 才是数字。
第二个参数表示搜索的起始位置,默认值是 0。
console.log([1, 2, 3].includes(2, 2)); // false
基本遵循严格相等(===),但是对于 NaN 的判断与 === 不同,includes 认为 NaN === NaN
console.log(NaN === NaN); // false
console.log([1, 2, NaN].includes(NaN)); // true
2、去重:
例如:对 [1,2,1] 进行去重:
const arr = [];
for (const item of [1, 2, 1]) {
if (!arr.includes(item)) {
arr.push(item);
}
}
console.log(arr); // (2) [1, 2]
Array.from():
1、基本用法:
转换成数组:
console.log(Array.from('str')); // (3) ["s", "t", "r"]
2、哪些可以通过 Array.from() 转换成数组:
(1)所有可遍历的:数组、字符串、Set、Map、NodeList、arguments
console.log(Array.from(new Set([1, 2, 1]))); // (2) [1, 2]
console.log([...new Set([1, 2, 1])]); // (2) [1, 2]
虽然该方法可以转换成数组,但不如展开运算符直观易表达,所以还是推荐展开运算符。
(2)拥有 length 属性的任意对象:
length的大小决定转换后数组的元素个数。虽然这种方式可以转成数组,但它只会将键名是数字且该数字小于length大小减1的键转出相应的值,其他键名和数字超出length-1的值均转成 undefined,且转换后数组元素的顺序是按键为数字的大小进行排序的。
// 键名是字符串:
const obj = {
'0': 'a',
'1': 'b',
name: 'Alex',
length: 3
};
console.log(Array.from(obj)); // (3) ["a", "b", undefined]
const number = {
'10':'李白',
'1':'10',
'3':'杜甫',
'2':'19',
'0':'alex',
length:5
}
console.log(Array.from(number)); // (5) ["alex", "10", "19", "杜甫", undefined]
3、第二个参数:
第二个参数相当于回调:作用类似于数组的 map 方法,用来对每个元素进行处理,将处理后的值放入返回的数组。
// 数组的map:
console.log(
[1, 2].map(value => {
return value * 2;
})
); // (2) [2, 4]
// 第二个参数:
console.log(Array.from('12', value => value * 2)); // (2) [2, 4]
console.log(Array.from('12').map(value => value * 2)); // (2) [2, 4]
4、第三个参数:
修改this指向:
Array.from(
'12',
value => {
console.log(this);
},
document
); // 2个window
// 这里是window是因为箭头函数修改不了this指向,在使用时this指向就确认了,想修改要用一般函数。
Array.from(
'12',
function () {
console.log(this);
},
document
); // 2个document
find() 和 findIndex():
find():找到满足条件的一个立即返回,不会在往后找了
findIndex():找到满足条件的一个,立即返回其索引
1、基本语法:
console.log(
[1, 5, 10, 15].find((value, index, arr) => {
// console.log(value, index, arr);
console.log(this);
return value > 9;
}, document)
); // 10
// 满足条件的第一个值,找到就返回不会继续往下找
findIndex() 也是如此:
console.log(
[1, 5, 10, 15].findIndex((value, index, arr) => {
// console.log(value, index, arr);
return value > 9;
}, document)
); // 2
2、应用:
筛除信息:
const students = [
{
name: '张三',
sex: '男',
age: 16
},
{
name: '李四',
sex: '女',
age: 22
},
{
name: '王二麻子',
sex: '男',
age: 32
}
];
console.log(students.find(value => value.sex === '女')); // {name: "李四", sex: "女", age: 22}
console.log(students.findIndex(value => value.sex === '女')); // 2
对象的新增方法:
Object.assign():
该方法是用来合并对象。
1、基本用法:
const apple = {
color: '红色',
shape: '圆形',
taste: '甜'
};
const pen = {
color: '黑色',
shape: '圆柱形',
use: '写字'
};
console.log(Object.assign(apple, pen)); // 4-1.Object.assign().html:24 {color: "黑色", shape: "圆柱形", taste: "甜", use: "写字"}
上面例子中大家可能觉得这个跟展开运算符作用有点相似。
展开运算符:
const apple = {
color: '红色',
shape: '圆形',
taste: '甜'
};
const pen = {
color: '黑色',
shape: '圆柱形',
use: '写字'
};
console.log({ ...apple, ...pen }); // {color: "黑色", shape: "圆柱形", taste: "甜", use: "写字"}
Object.assign()和展开运算符的结果结构上相同,但实际上还是有差别的,在前面我们知道展开运算符是在一个对象中展开,是返回一个新的对象,不会与前面的apple相等也不会与pen相等。
console.log({ ...apple, ...pen } == apple); // false
console.log({ ...apple, ...pen } == pen); // false
但是Object.assign()不一样,Object.assign 直接合并到了第一个参数中,返回的就是合并后的对象
console.log(Object.assign(apple, pen) === apple); // true
记住只是等于第一个参数apple,其他都不等
console.log(Object.assign(apple, pen) === pen); // false
还有就是,合并完之后apple里面的元素都变成了合并后的元素了。
console.log(Object.assign(apple, pen)); // {color: "黑色", shape: "圆柱形", taste: "甜", use: "写字"}
console.log(apple); // {color: "黑色", shape: "圆柱形", taste: "甜", use: "写字"}
console.log(pen); // {color: "黑色", shape: "圆柱形", use: "写字"}
有时不想改变原本对象里面的元素,就可以这样写:
console.log(Object.assign({}, apple, pen)); // {color: "黑色", shape: "圆柱形", taste: "甜", use: "写字"}
console.log(apple); // {color: "红色", shape: "圆形", taste: "甜"}
这样的话在合并完之后就不会改变原有对象里面的元素值了。
1、注意事项:
(1)基本数据类型作为源对象:
在Object.assign中第一个参数是目标对象,其他参数是源对象。即:
Object.assign(目标对象, 源对象1,源对象2,…);
// 与对象的展开类似,先转换成对象,再合并:
console.log(Object.assign({}, undefined)); // {}
console.log(Object.assign({}, null)); // {}
console.log(Object.assign({}, 1)); // {}
console.log(Object.assign({}, true)); // {}
console.log(Object.assign({}, ['1','2'])); // {0: "1", 1: "2"}
console.log(Object.assign({}, 'str')); // {0: "s", 1: "t", 2: "r"}
(2)同名属性的替换:
后面的直接覆盖前面的,这个大家可能一听就知道是是什么意思。
const apple = {
color: ['红色', '黄色'],
shape: '圆形',
taste: '甜'
};
const pen = {
color: ['黑色', '银色'],
shape: '圆柱形',
use: '写字'
};
console.log(Object.assign({}, apple, pen)); // {color: Array(2), shape: "圆柱形", taste: "甜", use: "写字"}
// 这里color是['黑色', '银色']
(3)应用:
一般用于合并默认参数和用户参数。
const logUser = userOptions => {
const DEFAULTS = {
username: 'ZhangSan',
age: 0,
sex: 'male'
}; // 默认信息
const options = Object.assign({}, DEFAULTS, userOptions);
console.log(options);
};
logUser(); // {username: "ZhangSan", age: 0, sex: "male"}
logUser({}); // {username: "ZhangSan", age: 0, sex: "male"}
logUser({ username: 'Alex' }); // {username: "Alex", age: 0, sex: "male"}
在上面案例中就利用了Object.assign合并的作用,在用户不传参时用默认参数,当用户传参时用用户的参数,还有个细节就是const options = Object.assign({}, DEFAULTS, userOptions);
中 userOptions 在 DEFAULTS 后面,为了就是当用户信息与默认信息重叠时,用户信息能覆盖默认信息。还有就是我们不需要给函数设置默认值即不需要设置为(userOptions = {})
,因为什么也不传时,即logUser();
的时候,相当于传进去个undefined,即const options = Object.assign({}, DEFAULTS, userOptions);
中的userOptions是undefined,而Object.assign会把undefined转化成一个{}再合并,所以不会报错!
Object.keys()、Object.values() 和 Object.entries():
1、基本用法:
const person = {
name: 'Alex',
age: 18
};
console.log(Object.keys(person)); // (2) ["name", "age"]
console.log(Object.values(person)); // (2) ["Alex", 18]
console.log(Object.entries(person)); // (2) [Array(2), Array(2)]
2、与数组类似方法的区别(简单了解一下即可):
console.log([1, 2].keys()); // Array Iterator {}
console.log([1, 2].values()); // Array Iterator {}
console.log([1, 2].entries()); // Array Iterator {}
console.log(person.keys); // undefined
对象的是构造函数的方法,数组是实例的方法。
数组的 keys()、values()、entries() 等方法是实例方法,返回的都是 Iterator
对象的 Object.keys()、Object.values()、Object.entries() 等方法是构造函数方法,返回的是数组
3、使用 for…of 循环遍历对象:
const person = {
name: 'Alex',
age: 18
};
for (const key of Object.keys(person)) {
console.log(key); // name age
}
for (const value of Object.values(person)) {
console.log(value); // Alex 18
}
for (const entries of Object.entries(person)) {
console.log(entries); // (2) ["name", "Alex"] (2) ["age", 18]
}
for (const [key, value] of Object.entries(person)) {
console.log(key, value); // name Alex age 18
}
注意:Object.keys()/values()/entires() 并不能保证顺序一定是你看到的样子,这一点和 for in 是一样的