zoukankan      html  css  js  c++  java
  • 近期写js库中遇到的一个判别的问题

    最近在写一个自己的js库,正写到数组包,在里面定义了一个排序,只对纯数字数据进行排序的方法,但是在测试的时候发现一个很诡异的问题,那就是传入一个对象的时候,它没有返回erroemsg而是返回了对象,上代码:

     1 array.sort=function(a){//only for num
     2 try{
     3 
     4   if(!a.some(function(x){return(typeof("string"))})){
     5   var max=a.length-1;
     6 
     7 for(var j=0;j<max;j++){
     8 
     9 for(var i=0;i<max;i++){
    10 
    11   if(a[i]>=a[i+1]){
    12    var tem=a[i+1];
    13     a[i+1]=a[i];
    14     a[i]=tem;
    15   }
    16 
    17 
    18 }
    19 }
    20 return a;
    21 }
    22 return -2
    23 
    24 
    25 }
    26 
    27 catch(ex){
    28   return -2;
    29 }
    30 
    31 }

    这是用的冒泡排序来进行数据排序的,可是传入对象后,没有返回-2.

    在大神的帮助下,知道了,原来在传入对象的时候,object.length会返回undefined,然后undefined在下面的max<j中会有一个隐式的类型转换变为NaN,然后for循环直接跳出return -2,不会throw error

    所以在这里,最难想到的是object.length会返回undefined,然后下面的转换,

    我试过传入null,则trycatch成功返回-2,而undefined也同样正确返回-2,所以这是一个特例,还是要注意一下。

  • 相关阅读:
    bottle support gb2312
    solr 1.4.0 multi core deploy
    view file encoding on ubuntu
    bottle support gb2312
    multicore solr deploy process(not complete)
    SOLR Performance Benchmarks – Single vs. Multicore Index Shards
    ubuntu查看进程占用端口命令
    seo
    ubuntu不能更新包
    bdb虽好,不要忘了monetDB哦
  • 原文地址:https://www.cnblogs.com/admos/p/4438288.html
Copyright © 2011-2022 走看看