Javascript - 打印对象和(不应该打印)功能

时间:2013-12-30 16:02:13

标签: javascript

我从一本书中写了一个方法来按属性对元素进行排序,但是,结合其他方法,我在数组中打印对象和一个我不想打印的函数,即我不知道我想打印

输出:

first - Ursula
second - Arsulu
first - Vasti
second - Vista
first - Xena
second - Xane
first - Yoh
second - Yho
first - Zoe  
second - Zeo
By
// Method by takes a member name string and returns
// a comparison function that can be used to sort an
// array of objects that contain that member.
Array.by = Array.by || function (name) {
  return function (o, p) {
  var a, b;
  if (typeof o === 'object' && typeof p === 'object' && o && p) {
      a = o[name];
      b = p[name];
    if (a === b) {
      return 0;
    }
    if(typeof a === typeof b) {  
      return a < b ? -1 : 1;
    }
    return typeof a < typeof b ? -1 : 1;
  } else {
    throw {
      name: 'Error',
      message: 'Expected an object when sorting by ' + name
    };
  }
 };
};

  // traverse each object of the object passed as parameter
  Object.iterate = Object.iterate || function(o)
  {
             'use strict';
         var key, item; 
             for(key in o)
             {
                if(o.hasOwnProperty(key)) 
                {    
                   item = o[key];
                   if(typeof item === "object")
                   {
                      Object.iterate(item); 
                   }    
                   else {
                      document.writeln(key + " - " + item + "<br>");  
                   }
                }    
              }
         };

    <script type="text/javascript" src="arrayLib.js"></script>
    <script type="text/javascript" src="objLib.js"></script>
    <script type="text/javascript">
       // <![CDATA[

             var a = 
             [
                  {first: 'Zoe',  second: 'Zeo'}, 
                  {first: 'Yoh',  second: 'Yho'}, 
                  {first: 'Xena', second: 'Xane'},
                  {first: 'Vasti', second: 'Vista'}, 
                  {first: 'Ursula', second: 'Arsulu'}
             ];
               a.sort(Array.by('first'));
               for(var i = 0; i < a.length; i++)
               {                        
                    Object.iterate(a[i]);
               }    
            // ]]>
      </script>    

1 个答案:

答案 0 :(得分:0)

抱歉,问题是

 <div>By</div>