1.Array
(1)数组是多个值的组合
在js中,数组中的元素类型可以不同。在js中数组的类型是object。
用于测试的index.html为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<p>The result is:</p>
<p id="test"></p>
<script src="script.js"></script>
</body>
</html>
arr[index]得到的是某个元素,arr得到的是整个数组的内容
var fruits = ["apple","orange","banana"]; // 创建数组的方式
document.getElementById("test").innerHTML = "fruits[0] = " + fruits[0] + "; fruits = " + fruits;
显示的结果为:
fruits[0] = apple; fruits = apple,orange,banana
(2)数组是object
数组与object的不同在于数组中元素的名称是数值,而object中元素的名称是字符串
var person = ["John","Smith",65]; // 注意这里用的括号和下面的不同
var person2 = {
firstName: "John",
lastName: "Smith",
age: 65
};
document.getElementById("test").innerHTML = person[0] + " " + person2["lastName"];
创建新的数组并且往数组中添加新的元素
var arr = [];
arr[0] = "apple";
arr[1] = "orange";
document.getElementById("test").innerHTML = arr;
显示的结果为:
apple,orange
2.Array Method
(1)toString()
只是将数组转换为string,在type上发生改变,但显示的结果不变。
(2)join()
var fruits=["apple","orange","banana"];
document.getElementById("test").innerHTML = fruits.join("*");
显示的结果为:
apple*orange*banana
(3)pop和push
var fruits=["apple","orange","banana"];
var temp = fruits.pop();
fruits.push("pear");
document.getElementById("test").innerHTML = fruits;
显示的结果为:
apple,orange,pear
(4)shift()
可以将第一个元素去掉,并且后面的元素全部往前移动一个位置,返回值是第一个元素。
var fruits=["apple","orange","banana"];
fruits.shift();
document.getElementById("test").innerHTML = fruits;
// 此时的fruits[0] = "orange";
显示的结果为:orange,banana
(5)delete
var fruits=["apple","orange","banana"];
delete fruits[0];
document.getElementById("test").innerHTML = fruits;
// 此时的fruits[0]位undefined
(6)splice(pos,num)
第一个参数是删除的元素的位置,第二个参数是删掉多少个元素
var fruits=["apple","orange","banana"];
fruits.splice(0,1);
document.getElementById("test").innerHTML = fruits;
显示的结果为:orange,banana
(7)concat
将两个数组结合在一起,使用的方式是:
arr1.concat(arr2);
(8)slice(pos)
从pos位置的那个元素开始到后面的元素提取出来
var fruits=["apple","orange","banana"];
var temp = fruits.slice(1);
document.getElementById("test").innerHTML = temp;
显示的结果为:orange,banana
3.Array Sort
(1)sort()和reserve()
/*
* @Author: Lin
* @Date: 2017-07-18 16:57:27
* @Last Modified by: Lin
* @Last Modified time: 2017-07-18 19:03:32
*/
var fruits=["apple","orange","banana"];
fruits.sort();
fruits.reverse();
document.getElementById("test").innerHTML = fruits;
显示的结果为:orange,banana,apple
(2)numeric sort
var points = [100, 2, 23, 12, 1, 24];
points.sort(function(a,b) {return a - b});
document.getElementById("test").innerHTML = points;
可以实现数字从小到大的排序:1,2,12,23,24,100
var points = [100, 2, 23, 12, 1, 24];
points.sort(function(a,b) {return b - a});
document.getElementById("test").innerHTML = points;
实现数字从大到小排序:100,24,23,12,2,1
(3)max和min
借用Math.max()和Math.min()来实现
var points = [100, 2, 23, 12, 1, 24];
document.getElementById("test").innerHTML=Math.max.apply(null,points);
注:Math.min.apply([1, 2, 3]) is equivalent to Math.min(1, 2, 3).
4.数组还可以是对象的数组
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}];