本文介绍了Array.prototype.reject():TypeError:.... reject不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习有关JavaScript函数编程的很酷的在线课程.直到讲师使用 Array.prototype.reject()并且它在运行时对我不起作用之前,我一直都很好.

I am taking a cool online course about functional programming in JavaScript. I was following along just fine until the instructor used the Array.prototype.reject() and it did not work for me at run time.

我想使用"reject"代替for循环,因为它的代码更少.但是,我的浏览器,NodeJS和Express Code控制台告诉我 reject不是函数.

I would like to use "reject" instead of a for loop because it is less code. But, my browser, NodeJS and Express Code consoles tell me that reject is not a function.

我研究了其他讨论 promise.reject 不是功能的文章,但是提供了对我的情况没有意义的解决方案.

I researched other articles that discuss promise.reject is not a function, but provide solutions that do not make sense to my scenario.

这是课程中的示例代码:

Here is the example code in the course:

var animals = [
    { name: 'Fluffykins',   species: 'rabbit' },
    { name: 'Caro',         species: 'dog' },
    { name: 'Hamilton',     species: 'dog' },
    { name: 'Harold',       species: 'fish' },
    { name: 'Ursula',       species: 'cat' },
    { name: 'Jimmy',        species: 'fish' }
];


var isDog = function(animal){
    return animal.species === 'dog';
}

var otherAnimals = animals.reject(isDog);

for循环的解决方法:

The work-around with a for-loop:

var notDogs = animals.filter(function(animal){
    return animal.species !== 'dog';
});

其输出是:

> notDogs
[ { name: 'Fluffykins', species: 'rabbit' },
  { name: 'Harold', species: 'fish' },
  { name: 'Ursula', species: 'cat' },
  { name: 'Jimmy', species: 'fish' } ]

请帮助我使用 Array.prototype.reject().

EditL

我在 GitHub /Array.prototype.reject)中找到了Array.prototype.reject()

I found Array.prototype.reject() at GitHub/Array.prototype.reject)

推荐答案

Array.prototype.reject 无关紧要,除非库/自定义代码添加了 reject 数组的方法.

Array.prototype.reject isn't a thing unless a library/custom code adds the reject method to Arrays.

要实现所需的功能,应使用 Array.prototype.filter 方法就像您已经使用的那样.我不确定您对此有何看法,因为您可以用相同的方式编写它:

To achieve what you want, you should use the Array.prototype.filter method like you already are. I'm not sure what you think is longer about it because you can write it the same way:

var animals = [
  { name: 'Fluffykins', species: 'rabbit' }, 
  { name: 'Caro', species: 'dog' }, 
  { name: 'Jimmy', species: 'fish' }
];

function noDogs(animal) {
  return animal.species !== 'dog';
}

var otherAnimals = animals.filter(noDogs);
console.log(otherAnimals);

这篇关于Array.prototype.reject():TypeError:.... reject不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 19:15