码迷,mamicode.com
首页 > 编程语言 > 详细

随题而学(二)多维数组转一维数组

时间:2015-04-07 19:12:26      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

多维数组转一维数组:[1,[2,3]] ==》 [1,2,3]

function tran(array){
    if(Object.prototype.toString.call(array) != ‘[object Array]‘){
        alert(Object.prototype.toString.call(array) + "非数组")
        return ;
    }
    
    var newArr = [];
    
    function trans(arr){
        for (var num = 0; num < arr.length;num ++){
            if(arr[num].length){
                trans(arr[num]);
            } else {
                newArr.push(arr[num]);
            }
        }
    }
    
    trans(array);
    return newArr;
}

 

[javascript] 
 
op = Object.prototype,  
ostring = op.toString,  
...  
function isFunction(it) {  
    return ostring.call(it) === ‘[object Function]‘;  
}  
function isArray(it) {  
    return ostring.call(it) === ‘[object Array]‘;  
}  

 


Object.prototype.toString  与 typeof 区别:

typeof

[plain]
  1. 在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 "object"。 
ECMA 对Object.prototype.toString的解释
[plain] 
  1. Object.prototype.toString ( )  
  2.   
  3. When the toString method is called, the following steps are taken:  
  4.   
  5. If the this value is undefined, return "[object Undefined]".  
  6. If the this value is null, return "[object Null]".  
  7. Let O be the result of calling ToObject passing the this value as the argument.  
  8. Let class be the value of the [[Class]] internal property of O.  
  9. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".  

http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2

[javascript]
var oP = Object.prototype,  
toString = oP.toString;  
  
console.log(toString.call([123]));//[object Array]  
console.log(toString.call(‘123‘));//[object String]  
console.log(toString.call({a: ‘123‘}));//[object Object]  
console.log(toString.call(/123/));//[object RegExp]  
console.log(toString.call(123));//[object Number]  
console.log(toString.call(undefined));//[object Undefined]  
console.log(toString.call(null));//[object Null] 

 

参考:http://my.oschina.net/sfm/blog/33197http://blog.csdn.net/spy19881201/article/details/12192767http://www.cnblogs.com/Aralic/p/4397015.html

随题而学(二)多维数组转一维数组

标签:

原文地址:http://www.cnblogs.com/yunkong/p/4399037.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!