JS数组、对象(方法汇总)

JS常用方法汇总

数组:

1. filter()

filter() 方法创建一个新的数组(不改变原始数组) ,新数组中的元素是通过检查指定数组中符合条件的所有元素。

var ages = [32, 33, 16, 40]
function checkAdult(age) {
   return age >= 18
}
function myFunction() {
   console.log(ages.filter(checkAdult)) // 输出 [32,33,40]
}

2. splice()方法在for循环中如何使用?

splice方法删掉一个元素后,后面紧邻的元素不会被遍历到

	for(let i=0, flag=true; i<list.length; flag ? i++ : i){
		if(lsit[i] === 'aaa' {
			list.splice(i, 1) // 删除第i个元素
			flag = false
		} else {
			flag = true
		}
	}

3. shift()

shift() 方法删除数组中开头元素,并返回该元素的值。

	const array1 = [1, 2, 3];
	const firstElement = array1.shift(); // 1
	console.log(array1); // Array [2, 3]

4. unshift()

unshift() 方法将元素添加到数组的开头,返回该数组的新长度

	const array1 = [1, 2, 3];
	console.log(array1.unshift(4, 5)); // expected output: 5
	console.log(array1); // expected output: Array [4, 5, 1, 2, 3]

5. pop()

pop()方法从数组中删除末尾元素,并返回该元素的值。

	let myFish = ["angel", "clown", "mandarin", "surgeon"];
	let popped = myFish.pop();// surgeon
	console.log(myFish); // ["angel", "clown", "mandarin"]

6. map()

map() 方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。

	const array1 = [1, 4, 9, 16];
	const map1 = array1.map(x => x * 2); // [2, 8, 18, 32] 

7. some()

some() 方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。【如果用一个空数组进行测试,在任何情况下它返回的都是false】

	const array = [1, 2, 3, 4, 5];
	let bool = array.some((element) => element % 2 === 0)
	console.log(bool) // true

---------------------------------------------------------------------------

对象:

1. Object.assign()

Object.assign方法用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target)。
如果target与source有同名属性,或多个source有同名属性,则后面的属性覆盖前面的属性

	const target = {a:1, b:1};
	const source1 = {b:2, c:2}
	const source2 = {c:3}
	Object.assign(target, source1, source2);
	console.log(target)   // {a:1,b:2,c:3}

2. 扩展运算符(…)

对象中的扩展运算符(…)用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中

	this.tempParam = { ...this.param } // 用法1
	this.tempdata.push(...res.data) // 用法2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值