企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
# 三个点(...) 有2个含义,分别表示 扩展运算符和 剩余运算符 ## 1 扩展运算符(spread) **数组展开** ``` function test(a,b,c){ console.log(a); console.log(b); console.log(c); } var arr = [1, 2, 3]; test(...arr); // 打印结果 // 1 // 2 // 3 ``` **将一个数组插入到另一个数据中** ``` var arr1 = [1, 2, 3]; var arr2 = [...arr1, 4, 5, 6]; console.log(arr2); // 打印结果 // [1, 2, 3, 4, 5, 6] ``` **字符串转数据** ``` var str='test'; var arr3= [...str]; console.log(arr3); // 打印结果 //  ["t", "e", "s", "t"] ``` ## 2 剩余运算符(rest) **当函数参数个数不确定时,用 rest运算符** ``` function rest1(...arr) { for (let item of arr) { console.log(item); } } rest1(1, 2, 3); // 打印结果 // 1 // 2 // 3 ``` **当函数参数个数不确定时的第二种情况** ``` function rest2(item, ...arr) { console.log(item); console.log(arr); } rest2(1, 2, 3, 4, 5); // 打印结果 // 1 // [2, 3, 4, 5] ``` **解构使用** ``` var [a,...temp]=[1, 2, 3, 4]; console.log(a); console.log(temp); // 打印结果 // 1 // [2, 3, 4] ``` # 历史遗留问题 ## 打乱数组 利用内置Math.random()方法。 ``` var list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; list.sort(() => { return Math.random() - 0.5; }); // 输出 [2, 5, 1, 6, 9, 8, 4, 3, 7] // Call it again [4, 1, 7, 5, 3, 8, 2, 9, 6] ``` sort 本质是通过遍历比较数组中两个值来进行排序 接着在sort回调函数中使用Math.random()方法产生一个0~1的随机数 减去0.5就会产生正数与负数概率相同的情况从而随机调换两个值的位置 输出结果就成为一个随机排序的数组 如果Math.random()减去的值大于0.5则会产生一个大概趋势为正序的数组 反之则产生大概趋势为倒序的数组 减去值越大(越小)趋势越明显