ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
> 数组的常用写法介绍 [TOC] ### 初始化 ~~~ var list = []; //var list = new Array(); list[0] = "aaa"; list[1] = "bbb"; list[2] = "ccc"; // 简介写法 //var list = ['xx', 'bb']; //var list = new Array('xxx', 'vvv'); ~~~ ## 向数组添加新元素:push() ~~~ var myarray = ["b1", "b2", "b3", "b4"]; myarray.push("b5"); ~~~ ## 合并多个数组:concat() ~~~ var arr1 = ["aaa", "bbb"]; var arr2 = ["ccc", "ddd", "eee"]; var newArr = arr1.concat(arr2); console.log(newArr) ~~~ ## 数组元素组合成字符串:join() ~~~ var fruits = ["aaa", "bbb", "ccc", "ddd"]; console.log(fruits.join('___')) ~~~ ## 数组排序:sort() > sort() 函数按照字符串顺序对值进行排序 > 但是,如果数字按照字符串来排序,则 "25" 大于 "100",因为 "2" 大于 "1",这个时候就需要用到闭包方式 ~~~ // 简单比值 var points = [5,1,10]; points.sort(function(a, b){ return a - b }) // 返回1,5,10 console.log(points) // 复杂比值 var list = [ {name:'wk11', points:11}, {name:'kk1', points:1}, {name:'xx20', points:20} ]; list.sort(function(a, b){ return a.points - b.points }) // 返回kk1, wk11,xx20 console.log(list) ~~~ ## 数组遍历:参考for篇