由于最近工作之余,使用vue较多,对于数组的操作也逐渐增多,特此整理js的数组,以便日后翻阅学习。
已经记不清其他语言中数组能够存放什么类型的数据,但是在js中数组的每一项都可以存放任何类型的数据,例如第一项存放字符串,第二项存放对象,依次类推。
let colors = ["red", "blue", "green" ]; console.log(colors[0]); // red colors[2] = "black"; // 修改 colors[3] = "yellow"; // 新增 console.log(colors.length); // 3,打印数组长度
小技巧:js中的数组的length不是只读的,可以通过length修改数组的长度
let arr = ["a", "b", "c"]; arr.length = 4; console.log(arr[3]); // undefined arr.length = 2; console.log(arr) // ["a", "b"] 可以删除末尾的值
如果我们在arr数组中添加arr[99] = ‘x‘;那么数组的长度为100,其余中间的值为undefined
es5新增的isArray可以帮我们解决这个问题(2019-12-19实际碰到的问题)
let arr = []; console.log(Array.isArray(arr)); // true
let colors = ["red", "blue", "green"]; console.log(colors.toString()); // red, blue, string console.log(colors.valueOf()); // 数组形式 console.log(colors); // 数组形式
同时我们可以使用join方法使数组转换为字符串
colors.join(‘,‘) // ‘‘red, blue, green‘‘
在js的数组中的栈(后进先出)方法推入是push方法,推出是pop方法。
使用unshift和pop 可以实现队列效果
重排序方法分为reverse()和sort()方法,前者是反转,这里详细介绍后者。
sort()方法默认按升序排列数组,但是是先调用数组中每一个项的toString()方法再进行比较,可能会与常识的顺序不同,所以我们需要添加方法来帮助我们排序。如下就是升序排列,降序只需将return的值互换即可。
function compare (value1, value2) { if (value1 < value2) { return -1; } else if (value1 > value2){ return 1; } else{ return 0; } } let values = [0, 5, 1, 10, 15]; values.sort(compare); // 0, 1, 5, 10, 15
需要买电影票的同志可以添加如下微信,价格低于app购买,全国支持,本人现实朋友,百分百可靠!
原文:https://www.cnblogs.com/swearBM/p/12070768.html