var arr =[1,2,3,4,5,6] //全文通用数组,个别除外
while
var i=0;
while(i<=arr.length-1){ //条件需要有限制,故<=,否则会死循环
console.log(arr[i],i)
i++;//更新下标
}
do while
var i=0;
do{
console.log(arr[i],i)
i++;
}while(i<=arr.length-1);//下标从0开始,length-1
for
for(var i = 0;i<arr.length;i++){
console.log(i,arr[i])
}
for in
for(key in arr){
console.log(key,arr[key])
}
ES6语法
//Array.fromIE不识别,IE的兼容写法。
//可以把类数组对象转换为真正的数组
if(!Array.from){
Array.from = function (el) {
return Array.apply(this, el);
}
}
Set
var a=[1,1,1];
var b=new Set(a);//去重
console.log(b)
b.add('li')//添加
b.delete('li') //删除
b.has('li') //返回true false;
b.clear()//清空
Map
var eMap = new Map([ ['a', 1],['b', 2],['c', 3] ]);
eMap.get('a') //1 //获取值
eMap.has('b')//true //检测key是否存在,返回true false;
eMap.delete('c') //删除
eMap.set('c',3) //添加
eMap.clear()//清空
//相当于返回一个新数组
arr.map(function(x){
if(x==3){
return x*3
}
return x
})
arr.map((x)=>{
if(x==3){
return x*3
}
return x
})
forEach
//两个参数 x数组内容,y数组下标
arr.forEach((x,y)=>{
console.log(x,y)
})
//不支持IE9以下,但不包括IE9,IE8兼容写法
//原文链接:https://www.cnblogs.com/guxiaosao/p/5179842.html
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function forEach( callback, thisArg ) {
var T, k;
if ( this == null ) {
throw new TypeError( "this is null or not defined" );
}
var O = Object(this);
var len = O.length >>> 0;
if ( typeof callback !== "function" ) {
throw new TypeError( callback + " is not a function" );
}
if ( arguments.length > 1 ) {
T = thisArg;
}
k = 0;
while( k < len ) {
var kValue;
if ( k in O ) {
kValue = O[ k ];
callback.call( T, kValue, k, O );
}
k++;
}
};
}
for of
//支持大多数类数组对象 参考https://developer.mozilla.org/en-US/docs/Web/API/NodeList
//不支持普通对象遍历 如:{ } 会报错 is not iterable
//IE不支持
for(var i of arr){
console.log(i,arr[i-1])//for of的下标从1开始,故减1
如果您觉得本文的内容对您的学习有所帮助:
关键字:
jquery