代码之家  ›  专栏  ›  技术社区  ›  roundcrisis

Javascript对象数组到字符串数组,更简单的方法?

  •  3
  • roundcrisis  · 技术社区  · 16 年前

    有没有更好的办法?

    var justColumnNames = new Array();    
    for( i= 0; i< columnsInfo.length; i++)
    {
       justColumnNames[i] = columnsInfo[i].Name;
    }
    

    (顺便说一句,我在页面中提供了Extjs,我不能真正使用任何其他库)

    3 回复  |  直到 16 年前
        1
  •  5
  •   Upperstage    16 年前
    Ext.each( columnsInfo, function(elem){
        justColumnNames.push(elem.name);
    });
    
        2
  •  2
  •   Community Mohan Dere    9 年前

    你要找的是一个 map() this question 链接到一些您可以使用的插件。

    justColumnNames = columnsInfo.map(function(elem) { elem.Name });

        3
  •  -1
  •   slebetman    16 年前

    您可以轻松地在javascript中添加语法糖。一个常见的方法是为数组实现foreach/map/filter方法。大多数图书馆都这样做。我的实施:

    // List object, inherits from Array
    function List (array) {
        // Allow List constructor to convert
        // Array object into List object:
        if (array !== undefined) {
            this.push.apply(this,array)
        }
    
        // each() method. A cross between map and filter:
        this.each = function (callback) {
            var ret = new List();
            for (i=0,l=this.length;i<l;i++) {
                var r = callback(this[i],i);
                if (r !== undefined) {
                    ret.push(r);
                }
            }
            return ret;
        }
    }
    List.prototype = new Array();
    
    // Direct translation of your code:
    var justColumnNames = new List();
    justColumnNames.each(function(n,i){
       n = columnsInfo[i].Name;
    });
    
    // Or the more brief:
    var justColumnNames = new List(columnsInfo).each(function(n){return n.Name});
    

    Array.prototype.each = function (callback) {
            // see implementation above ...
    }
    

    但我通常不喜欢修改本机对象。