JS和jquery的几个令人迷惑的问题之三-数组

14 篇文章 0 订阅
7 篇文章 0 订阅

1.数组

1.1.数组元素的读写

> var a=["world"]
undefined
> value=a[0]
'world'
> a[1]=3.14
3.14
> i=2
2
> a
[ 'world', 3.14 ]
> a[i]=3
3
> a[i+1]="hello"
'hello'
> a
[ 'world',
  3.14,
  3,
  'hello' ]
> a[a[i]]=a[0]
'world'
> a
[ 'world',
  3.14,
  3,
  'world' ]
> a.length
4

1.2.稀疏数组

在一个数组中有undefined这样的元素,就称为稀疏数组

> var a1 = [,,,]; // This array is [undefined, undefined, undefined]
undefined
> var a2 = new Array(3); // This array has no values at all
undefined
> 0 in a1 // => true: a1 has an element with index 0 这里和书本里面预期不一致。nodejs里面的实现可能不一样吧。
false
> 0 in a2 // => false: a2 has no element with index 0
false
> a1
[ , ,  ]
> a2
[ , ,  ]
> a1[0]
undefined
> a2[0]
undefined
> var b1=[,]
undefined
> var b2=[undefined]
undefined
> 0 in b1
false
> 0 in b2
true
>
1.3.数组元素的添加和删除

push()

pop()

unshift()

shift()

splice()是个通用的方法用来插入、删除或替换数组元素。

1.4.数组遍历

for/in循环

for循环


如果算法依赖于遍历的次序,最好不要使用for/in循环而用常规的for循环或者forEach()方法

var data = [1,2,3,4,5]; // This is the array we want to iterate
var sumOfSquares = 0; // We want to compute the sum of the squares of data
data.forEach(function(x) { // Pass each element of data to this function
               sumOfSquares += x*x; // add up the squares
            });
sumOfSquares // =>55 : 1+4+9+16+25


稀疏数组的遍历

for(var index in sparseArray) {
  var value = sparseArray[index];
  // Now do something with index and value
}
或者更进一步过滤掉不想要的属性
for(var i in a) {
  if (!a.hasOwnProperty(i)) continue; // Skip inherited properties
  // loop body here
}

1.5.数组方法

1.5.1.ECMASCRIPT3中的数组方法

join

reverse

sort

concat

slice

splice

push

 pop

unshift

shift

toString

toLocaleString

1.5.2.ECMASCRIPT5中的数组方法

forEach

map

filter

every

some

reduce

reduceRight

indexOf

lastIndexOf

1.6.数组类型

Array.isArray()

instanceof操作符,尽量不要使用这个操作符,不能被视为一个可靠地数组检测方法。因为instanceof的意思就是作为一个类构造函数的实例,在多窗口或窗体(frame)的web浏览器中,会存在多个类构造函数,就会发生混淆。

下面是一个兼容ECMASCRIPT3和ECMASCRIPT5的做法

var isArray = Function.isArray || function(o) {
  return typeof o === "object" &&
  Object.prototype.toString.call(o) === "[object Array]";
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值