1)、怎么判断javascript中的某一变量是二维数组?

(2)、var arrs = [hello,1,[1,2,3],["a","b"]];
怎么把数组arrs中的每个元素依次显示出来?(显示出来的顺序依次为: hello 1 1 2 3 a b )

第1个回答  2011-10-21
要是你的问题1是作为问题2的前提的话,我可以告诉你这个完全没有必要 ;
var array = arrs.spilit(",")
var temp
var length = array.length
for (temp=0;temp<length;temp++)
{
if (array[temp]<>"[" && array[temp]<>"]")
{
alert(array[temp]);
}
}追问

if (array[temp]"[" && array[temp]"]")
这句是什么意思啊?这个:也没明白是什么意思,您能解释一下吗?谢谢了

追答

就是不等于,上面的语句就是去除拆分后数组中得"["和"]",这样就不会输出了。

第2个回答  2011-10-19
<script>
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
var arrs = ["hello",1,[1,2,3],["a","b"]];
for(var i=0;i<arrs.length;i++){
if(isArray(arrs[i])){
for(var j=0;j<arrs[i].length;j++){
alert(arrs[i][j]);
}
}else{
alert(arrs[i]);
}
}
</script>追问

这句:return Object.prototype.toString.call(o) === '[object Array]';
看的不太懂,您能帮我详细解释一下吗?谢谢啦,我一定给您追加分

追答

采用Object.prototype.toString.call(o)来检测
为什么要用Object.prototype.toString而不是Function.prototype.toString或者其它?这是和他们的toString解释方式有关系的。下面是ECMA中对Object.prototype.toString的解释:
Object.prototype.toString( )When the toString method is called, the following steps are taken:1. Get the [[Class]] property of this object.2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.3. Return Result (2)
其过程简单说来就是:1、获取对象的类名(对象类型)。2、然后将[object、获取的类名、]组合并返回。
ECMA中对Array有如下说明:
The [[Class]] property of the newly constructed object is set to “Array”.
因此我们用如下代码来检测数组:
function isArray(o){
return Object.prototype.toString.call(o) === '[object Array]';
}
-----------------------------------------------
上面的是我从网络上面找的。人家解释的比较详细,这个估计理解起来有点费劲,call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。意思就是用括号里面的对象替换被调用的对象。Object.prototype.toString 返回的就是 "[object Undefined]" 没有什么为什么,ECMA就是这样规定。然后Object.prototype.toString.call("某类型") 那么打印出来的就是 "[object 某类型]" 。===的意思就是不做类型转换直接比较,== 会默认自动转换成匹配类型在做比较。

本回答被提问者采纳

相关了解……

你可能感兴趣的内容

大家正在搜

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网