ES6-新增方法

一、includes

判断字符串中是否含有某些字符,或数组是否包含某个元素

1、基本用法

console.log('abc'.includes('a'));//true
console.log('abc'.includes('d'));//false
console.log([1,2,3].includes(1));//true
console.log([1,2,3].includes('1'));//false

2、第二个参数
表示开始搜索的位置,默认是0

console.log('abc'.includes('a',1));//false

二、padStart()和padEnd()

补全字符串长度

1、基本用法

console.log('x'.padStart(5,'ab'));//ababx
console.log('x'.padEnd(5,'ab'));//xabab

2、注意事项

  • 原字符串的长度,等于或大于最大长度,不会消减原字符串,字符串补全不生效,返回原字符串
console.log('xxx'.padEnd(2,'ab'));//xxx
  • 用来补全的字符串与原字符串长度之和超过了最大长度,截去超出位数的补全字符串,原字符串不动
console.log('abc'.padStart(10, '0123456789'));//0123456abc
  • 如果省略第二个参数,默认使用空格补全长度

三、trimStart()和trimEnd()

清除字符串的首或尾空格,中间的空格不会清除

四、数组的Array.from()

将其他数据类型转换成数组
所有可遍历的
数组、字符串、Set、Map、riodeList、arguments
拥有length属性的任意对象

1、基本用法

console.log(Array.from('str'));//[ 's', 't', 'r' ]
const obj = {
    
    
	'0':'a',
	'1':'b',
	name: 'Alex',
	length: 3
};
console.log(Array.from(obj));//[ 'a', 'b', undefined ]

2、第二个参数
作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组

console.log(
	[1,2].map(value => {
    
    return value * 2})
);//[ 2, 4 ]
console.log(Array.from('12', value => value * 2));//[ 2, 4 ]

五、find()和findIndex()

find():找到满足条件的一个立即返回
findIndex():找到满足条件的一个,立即返回某索引

1、基本用法

console.log(
	[1,5,10,15].find((value) =>{
    
    
	return value > 9;
	})
);//10

console.log(
	[1,5,10,15].findIndex((value) =>{
    
    
	return value > 9;
	})
);//2

六、Object.assign()

合并对象
相同的属性后面的会覆盖前面的
可以合并多个对象

const apple = {
    
    
	color: '红色',
	shape: '圆形',
	taste: '甜'
};
const pen = {
    
    
	color: '黑色',
	shape: '圆柱形',
	use: '写字'
};

console.log(Object.assign(apple,pen));
//{ color: '黑色', shape: '圆柱形', taste: '甜', use: '写字' }
console.log(apple)//{ color: '黑色', shape: '圆柱形', taste: '甜', use: '写字' }
console.log(Object.assign(apple,pen)===apple)//true

七、Object.keys). Object.values()和Object.entries()

获取对象的键值

const person = {
    
    
	name: 'Alex',
	age: 18
};
console.log(Object.keys(person));//[ 'name', 'age' ]
console.log(Object.values(person));//[ 'Alex', 18 ]
console.log(Object.entries(person));//[ [ 'name', 'Alex' ], [ 'age', 18 ] ]

猜你喜欢

转载自blog.csdn.net/qq_42042158/article/details/126008039
今日推荐