看arry相关笔记

创建数组:

1. var colors = new Array ();         //括号中可以填入项目数量
2. var colors = new Array ("red","blue","green");    //可以之间填入数组包含的项

PS:new可以省略,第二种的括号可以改为方括号。

读取与设置数组的值:

用方括号,并填入基于0的数字

var colors = new Array ["red","blue","green"];
array [1] = "blue"    //显示第二项
array [3] = "black"    //增加第四项

数组的项数保存在length属性中:

var colors = new Array ["red","blue","green"];    //创建一个有三个字符串的数组
var name = [];                     //创建一个空数组
alert(colors.length);          //3
alert(colors.length);          //0

可以设置length属性从数组的末尾移除项

var colors = new Array ["red","blue","green"];    //创建一个有三个字符串的数组
colors.length = 2;
alert(colors[2]);       //undefined 

colors有3个值,将length属性设置成2会移除最后一项,再访问时显示undefined

添加新项

var colors = new Array ["red","blue","green"];    //创建一个有三个字符串的数组
colors.length = 4;
alert(colors[3]);       //undefined 

将length属性设置大于数组项数,新增的项为undefined

var colors = new Array ["red","blue","green"];
colors[colors.length] = "black";  //在位置3添加黑色
colors[colors.length] = "brown";  //在位置4添加棕色

PS:数组的最后一项索引为length-1

你可能感兴趣的:(看arry相关笔记)