从数组中删除空字符串

时间:2013-11-29 18:54:36

标签: javascript arrays node.js

我知道还有其他页面,但我正在努力让自己的工作,我不知道为什么它不起作用。我是node.js的新手。

for (var index in output)
{
    if (opt.options.showEmpty != true)
    {
        var check = arrayIsEmpty(output[index]);

        if ( check == true )
        {
            continue;
        }
        else
        {
            var array = removingEmptyString(output[index]);

            console.log(index + "\t" + array);
            //console.log(index+ "\t" + output[index]);
        }
    }
}

function removingEmptyString(array)
{
    var newArray;

    for( var i = 0; i < array.length; i++)
    {
        if(array[i] != "" || array[i] != null)
        {
            newArray[i] = array[i];
        }
    }

    return newArray;
}

我的结果是树,,,我以前在我写的代码之前得到了。现在我得到错误

    newArray[i] = array[i];
                                ^
TypeError: Cannot set property '0' of undefined
    at removingEmptyString (librarySeeker.js:130:18)
    at result (librarySeeker.js:76:19)
    at /async/lib/async.js:226:13
    at async/lib/async.js:113:25
    at async/lib/async.js:24:16
    at async/lib/async.js:223:17
    at /async/lib/async.js:510:34
    at IncomingMessage.<anonymous> (pull.js:295:10)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:910:16

3 个答案:

答案 0 :(得分:6)

您可以使用.filter method in Array's prototype

var pirate = ['a','1','',0];

function arr (value) {
  return value.filter(function (item) {
    return item !== '';
  });
}

arr(pirate);
// <- ['a','1',0]

作为替代方案,您可能需要考虑将回调命名为.filter

var pirate = ['a','1','',0];

function worthy (value) {
  return value !== '';
}

pirate.filter(worthy);
// <- ['a','1',0]

答案 1 :(得分:0)

本着学习的精神,这是您的解决方案的工作版本:

function removingEmptyString(array) {
    'use strict';
    var newArray = [];  // don't forget to initialize it
    for( var i = 0, len = array.length; i < len; i += 1) {
        if(typeof array[i] === 'string' && array[i].length > 0) {
            // add the string to the end of the new array
            newArray.push(array[i]);
        }
    }
    return newArray;
}

答案 2 :(得分:0)

错误是说newArray尚未初始化,因此无法将0属性分配给未定义的对象。

您可以改进功能以使其正常工作:

function removingEmptyString(array){
  var newArray = [];

  for( var i = 0; i < array.length; i++){
    // empty string and null are falsy values by default is js
    if(array[i])
    {
    // use this if you want to keep "undefined" values in the newArray in place
    // of the null ones in the original array
        newArray[i] = array[i];

    // otherwise just push the values in the new array
    // newArray.push(array[i]);
    }
  }

  return newArray;
}