剩余参数
- 剩余参数语法允许我们将一个不定数量的参数表示为一个数组
- 不定参数定义方式,这种方式很方便的去声明不知道参数情况下的一个函数
const chengji = (...args) => {
let chengji = 1;
args.forEach((item) => {
chengji *= item;
})
return chengji;
}
console.log(chengji(20,13))
console.log(chengji(20,14,8,12))
let stars = ['刘亦菲', '张靓颖', '唐嫣'];
let [s1, ...s2] = stars;
console.log(s1);
console.log(s2);
- 其中 … 称之为展开运算符
- 扩展运算符可以将数组或者对象转为用逗号分隔的参数序列
let number = [1, 2, 3];
console.log(...number);
console.log(1, 2, 3);
console.log('------------数组合并案例--------------------');
var arr1 = [1, 2, 3]
var arr2 = [4, 5, 6]
var arr3 = [...arr1, ...arr2]
console.log(arr3);
console.log('-----------求最大值----------------');
var maxArr = [1, 52, 13, 43, 55, 67]
console.log(Math.max.apply(Math, maxArr));
console.log(Math.max(...maxArr));
console.log('----------------3.将伪数组转化为真正的数组----------------');
var liArr = document.querySelectorAll('li');
console.log(liArr);
console.log([...liArr]);
- 利用Array.from 方法将伪数组转换为真正的数组
const arraylike = {
'0': 'gy',
'1': 'ckx',
'2': 'gyq',
'3': 'ghy',
length: 4
}
console.log('----------------------伪数组-----------------------------');
console.log(arraylike);
console.log('----------利用Array.from 方法将伪数组转换为真正的数组---------');
var newArray = Array.from(arraylike);
console.log(newArray);
- 利用Array.from 方法将伪数组转换为真正的数组的第二个参数
const arraylike2 = {
'0': 1,
'1': 2,
'2': 3,
'3': 4,
length: 4
}
var newArray2 = Array.from(arraylike2, item => item * 2);
console.log(newArray2);