Javascript有一个函数返回没有值

时间:2017-08-01 19:13:17

标签: javascript arrays comparison

如果两个数组之间的两个值相同,我一直试图创建一个不会返回任何值的函数。我已经在这里和谷歌上搜索了我的问题,我找到的所有内容都表明函数可以返回一个值,并且没有办法避免这样做。所以我直接询问是否有办法,如果不是,我怎么能绕过我想做的事情?



var bannedValues = [2, 4, 6, 8]; //Even numbers 1-8
var inputValues = [1, 2, 3, 4, 5, 6, 7, 8]; //All numbers 1-8

var filterValues = function(value) 
{
  for (var number of bannedValues) 
  {
    if (value == number) 
    {
      return; //I want this to return absolutely nothing, not even an empty value
    }
  }
  return value;
}

var filteredValues = inputValues.map(filterValues);

console.log(filteredValues); 
/* The array just gains "undefined" values in the places I want there 
to be no value, so the array is a length of 8 instead of the 4 I want. 
Can I somehow take those out or can I just not have them there in the first place? */




3 个答案:

答案 0 :(得分:1)

如果您正在使用map,则实际上是在遍历数组并在必要时对其进行操作,但这不会从数组中删除项目。而不是地图尝试过滤器

var bannedValues = [2, 4, 6, 8]; //Even numbers 1-8
var inputValues = [1, 2, 3, 4, 5, 6, 7, 8]; //All numbers 1-8

var filterValues = function(value) {
  return bannedValues.indexOf(value)===-1;
}

var filteredValues = inputValues.filter(filterValues);

console.log(filteredValues); 

结果将是

(4) [1, 3, 5, 7]

答案 1 :(得分:1)

使用Array.filter()方法:

var bannedValues = [2, 4, 6, 8]; //Even numbers 1-8
var inputValues = [1, 2, 3, 4, 5, 6, 7, 8]; //All numbers 1-8

filteredValues = inputValues.filter( function( el ) {
  return bannedValues.indexOf( el ) < 0;
} );

/*This is another way to do it, but not supported in IE*/
filteredValues = inputValues.filter( function( el ) {
  return !bannedValues.includes( el );
} );

console.log(filteredValues);

Lodash还有一个实用功能:see here

答案 2 :(得分:0)

JavaScript函数始终具有返回值。你无能为力。

我认为不可能告诉显式返回undefined的函数和只返回没有值表达式的函数之间的区别。

如果您想要喜欢 .map(),但可以选择跳过值,请改用.reduce()

var filterValues = function(accumulator, value) 
{
  for (var number of bannedValues) 
  {
    if (value == number) 
    {
      return accumulator;
    }
  }
  accumulator.push(value);
  return accumulator;
}

var filteredValues = inputValues.reduce(filterValues, []);
相关问题