最近用到JS中三个点的语法,在网上搜了一下,写的也挺多,我总结了一下一些常用的用法,并不完整,但常用够了,简单明了。直接上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>三个点的用法</title>
</head>
<body>
<script type="text/javascript">
/**
* @author newboy
*/
/**
* 1. 类似于java中可变参数
* @param args
*/
function fun1(...args) {
//内部是一个数组
for (let arg of args) {
document.write(arg + "<br/>");
}
}
fun1(1, "a", true);
/**
* 2. 将数组做为函数参数
*/
function fun2(x, y, z) {
document.write(x + "<br/>");
document.write(y + "<br/>");
document.write(z + "<br/>");
}
let arr = [3, 4, 5];
//类似于将数组的括号去了
fun2(...arr);
/**
* 3.字符转数组
*/
let str = "hello";
let arr1 = [...str];
document.write(arr1 + "<br/>"); //h,e,l,l,o
/**
* 4.复制对象
*/
let person = {
name: "newboy",
age: 20,
sex: "男"
}
//复制对象,并且修改属性
let person1 = {...person, age: 18};
console.log(person1); //{name: 'newboy', age: 18, sex: '男'}
/**
* 5. 解构赋值
*/
let {name,...others} = person;
console.log(name); //newboy
console.log(others); //{age: 20, sex: "男"}
/**
* 6.合并数组
*/
let a1 = ["a","b","c"];
let a2 = [1,2,3];
let a3 = [...a1, ...a2];
document.write(a3 + "<br/>"); //a,b,c,1,2,3
</script>
</body>
</html>