1. 为什么要用数组?
管理一组数据。
用购物清单打比方:
变量: 每个要买的东西都写在一张便签上。
数组: 一张便签上可以写一组要买的东西。
2. 创建数组
[ ]; //empty array var colors = ["red", "green", "blue", "yellow", "purple"]; var vowels = [ // format for human reading "a", "e", "i", "o", "u" ];3. 访问数组元素
colors[1];
4. 设置/修改 数组元素
colors[0] = 'gray'; // 修改第一个元素。为什么第一个元素的下标是0呢? colors[100] = 'black'; // 数组元素不必连续,这里不会发生越界行为。中间会插上 undefined colors[43]; // undefined5. 数组中可以是混合的数据类型
var mix = [3, "hello", ['a', 'e', 'i', 'o', 'u'], "world"]; mix mix[1] mix[2] mix[2][3]6. 数组的长度
mix.length mix[mix.length - 1] // 数组中的最后一个元素 7. 追加元素 var animals = [ ]; animals.push("Cat"); // 尾部追加 animals.push("Dog"); animals.unshift("Monkey"); // 头部追加8. 删除元素
var lastAnimal = animals.pop( ); // remove last element, and return it. lastAnimal; animals; animals.unshift(lastAnimal); var firstAnimal = animals.shift( ); // remove first element, and return it. firstAnimal; animals; push/pop unshift/shift9. 连接两个数组
var beasts = ['horse', 'fox', 'wolf', 'tiger']; var birds = ['eagle', 'seagull', 'parrot', 'macaw']; var animals = beasts.concat(birds); animals; beasts; birds; 10. 连接多个数组 var poultries = ['cock', 'hen', 'goose', 'duck']; animals = []; animals; animals = beasts.concat(birds, poultries);11. 查找元素在数组中的位置
animals.indexOf('fox'); animals.indexOf('pig'); var insects = ['Bee', 'Ant', 'Bee', 'Bee', 'Ant']; insects.indexOf('Bee'); // 返回第一个遇到的元素位置12. 数组变string
animals.join(); // comma as separators animals.join('-'); // hyphen as separators animals.join(' * '); // spaces and asterisk as separators13. 例子:去旅游,原路返回
var cities = [ ]; cities.push('Beijing'); cities.push('Tianjin'); cities.push('Tangshan'); cities.push('Qinhangdao'); cities.push('Huludao'); cities.push('Shenyang'); cities.push('Changchun'); cities.push('Haerbin'); cities.pop(); cities.pop(); cities.pop(); cities.pop(); //.... stack -> 烙饼 LIFO : Last In First Out queue -> 排队买票 FIFO : First In First Out14. 例子: 中午去哪里吃饭?随机选择饭馆。
准备知识:
Math.random(); // 生成 0 到 1 之间的随机数 Math.random() * 10; // 变成 0 到 10 之间的数 Math.floor(3.14); // 下取整 Math.floor(Math.random() * 10); // 变成 0 到 10 之间的整数 算法: var restaurants = ['三和屋', '秦面轩', '李连贵肉饼', '必胜客', '和合谷', '小院时光', '雕刻时光']; var index = Math.floor(Math.random() * restaurants.length); restaurants[index];
15. 思考题:
上图中,为什么两次都是 "小院时光"? 不是说,随机选择吗?
function lunch() { var restaurants = ['三和屋', '秦面轩', '李连贵肉饼', '必胜客', '和合谷', '小院时光', '雕刻时光']; var index = Math.floor(Math.random() * restaurants.length); return restaurants[index]; } lunch();