0
点赞
收藏
分享

微信扫一扫

js中数组的学习--数组的访问以及遍历数组

Gascognya 2022-02-28 阅读 87

1.数组访问

数组变量名[索引];

//如果索引小于数组的长度,返回对应项的值

var arr=[1,2,3,4];
console.log(arr[0]);//1 如果索引小于数组的长度,返回对应项的值

//如果索引大于等于数组的长度,返回undefined

console.log(arr[5]);//如果索引大于等于数组的最大下标,则访问不到,返回undefined

//如果给索引大于等于数组的长度的位置设置了值,数组自动增加到该索引值加1的长度

arr.length=8;
console.log(arr);//[ 1, 2, 3, 4, <4 empty items> ] 

//在数组中增加数据元素

arr[4]='terry';
arr[5]='larry';
console.log(arr,arr.length,arr[4]);//[ 1, 2, 3, 4, 'terry' , 'larry' ] 5  terry

2.遍历数组

 for(初始条件;结束条件;迭代条件){
            //循环体
 }
 //增强版
 for(var index in arr){
            //循环体
 }

//使用for遍历数组

var arr=['hello',1,true,null];
//下标  去循环遍历数组
for(var i=0;i<arr.length;i++){
    var result=arr[i];
    console.log(result,'循环遍历数组');
}
/* hello 循环遍历数组
1 循环遍历数组
true 循环遍历数组
null 循环遍历数组 
*/

//使用增强版遍历数组

for(let index in arr){
    console.log(index,arr[index]);
}
/* 0 hello
1 1
2 true
3 null */
举报

相关推荐

0 条评论