<html>
<head>
<title></title>
<script>
function show(){
var studentList = new Array();
studentList['一班']='张三';
alert(studentList['一班']);
studentList[0]='1111';
studentList[1]='2222';
for(var i = 0; i < studentList.length; i++){
alert(studentList[i]);
}
}
</script>
<body onload="show()">
</body>
</html>这么一段很简单的代码,让我非常纠结,JS里面的Array对象,很多技术文档上面都说是通过下标进行存储的,但是我直接通过Key-Value的方式也能够把‘张三’存储进去,并且能够通过key取出值,很明显,‘张三’这个值已经可以确定存入到了studentList里面,但是问题来了,明眼人都知道,下面通过循环进行取值的时候是肯定取不出来'张三'的值的,那么,在这个studentList里面,JS底层到底是把所谓的下标,也就是var i当做字符判断来通过Key-Value来匹配Array里面的值,还是我用下标存储和用Key-Value存储在studentList里面的根本就是两个不同的区域呢?急求高手解答
<head>
<title></title>
<script>
function show(){
var studentList = new Array();
studentList['一班']='张三';
alert(studentList['一班']);
studentList[0]='1111';
studentList[1]='2222';
for(var i = 0; i < studentList.length; i++){
alert(studentList[i]);
}
}
</script>
<body onload="show()">
</body>
</html>这么一段很简单的代码,让我非常纠结,JS里面的Array对象,很多技术文档上面都说是通过下标进行存储的,但是我直接通过Key-Value的方式也能够把‘张三’存储进去,并且能够通过key取出值,很明显,‘张三’这个值已经可以确定存入到了studentList里面,但是问题来了,明眼人都知道,下面通过循环进行取值的时候是肯定取不出来'张三'的值的,那么,在这个studentList里面,JS底层到底是把所谓的下标,也就是var i当做字符判断来通过Key-Value来匹配Array里面的值,还是我用下标存储和用Key-Value存储在studentList里面的根本就是两个不同的区域呢?急求高手解答
studentList['一班']='张三';
这两行用java表示相当于:
public MyArray extends Array{
public String 一班;//这是新加了个属性,与数组无关
}MyArray studentList =new MyArray ();
studentLint.一班="张三";
studentList['一班']='张三';这一句根本就没有操作到studengList这个数组,因为它要数字下标才能操作到。而是将‘张三’这个值给了studentList['一班'] 这样一个变量;
你的代码就跟下面的代码是一个意思 :
<script>
function show(){
var studentList = new Array();
t='张三';
alert(t);
studentList[0]='1111';
studentList[1]='2222';
for(var i = 0; i < studentList.length; i++){
alert(studentList[i]);
}
}
</script>
我又重新测试了一遍,我发现在studentList的长度只有2,也就是说它里面只有1111和2222这两个值。
studentList['一班']只是添加的一个属性。
谢谢了!