javascript - 当被过滤的数组包含 JSON 数据时,为什么我会收到 'cannot read property ' filter' of undefined' ?

标签 javascript arrays json api filter

以下代码

const endpoint = 'https://raw.githubusercontent.com/Hipo/university-domains-list/master/world_universities_and_domains.json';
const universities = [];

fetch(endpoint)
    .then(results => results.json())

    .then(data => universities.push(...data));

console.log(universities);

function findMatches(wordToMatch, universities) {
    return universities.filter(uni => {
        const regex = new RegExp(wordToMatch, 'gi');
        return uni.name.match(regex)
    })
}

export default findMatches;

返回以下错误

'Uncaught TypeError: Cannot read property 'filter' of undefined'

我可以使用 console.log(universities) 记录数据。那么为什么我不能过滤它呢?仅供引用,数据是对象数组。非常感谢任何帮助。谢谢。

最佳答案

您需要在 findMatches 函数中删除 universities 作为参数,因为它会覆盖本地 universities 变量的值:

function findMatches(wordToMatch) {
    return universities.filter(uni => {
        const regex = new RegExp(wordToMatch, 'gi');
        return uni.name.match(regex)
    })
}

然后您可以继续使用 findMatches 函数,如下所示:

findMatches("hi") // returns a filtered array

编辑:

您的代码中有竞争条件,其中可能会调用 findMatches 在您的 fetch 完成之前。要解决此问题,findMatches 应返回如下 promise :

const endpoint = 'https://raw.githubusercontent.com/Hipo/university-domains-list/master/world_universities_and_domains.json';
const universities = [];

const promise = fetch(endpoint)
    .then(results => results.json())

    .then(data => universities.push(...data));

console.log(universities);

function findMatches(wordToMatch) {
    return promise.then(() => universities.filter(uni => {
        const regex = new RegExp(wordToMatch, 'gi');
        return uni.name.match(regex)
    }));
}

findMatches("hi").then(arr => console.log(arr));

如果您绝对确定 findMatches 始终会在 fetch 完成后被调用,则可以采用第一个解决方案。否则,强烈建议您使用第二种使用 promise 的解决方案。

关于javascript - 当被过滤的数组包含 JSON 数据时,为什么我会收到 'cannot read property ' filter' of undefined' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47371364/

相关文章:

javascript - 三星智能电视应用程序使用Google API?

javascript - 在 JS 中使用 php 设置 cookie 在第 29 行给我一个错误,从 PHP 代码返回一个变量?

javascript - 使用 d3 拖动行为的原点为树节点创建 "drag handle"

javascript - 在javascript中使用二维数组获得最高频率

c - 如何从文件中读取数字并将其分配给它们的实际含义

python - Numpy 数组的长整数形状

json - 几秒钟后快速刷新 JSON 数据

php - 使用 javascript 验证输入数组

javascript - GSON 不是对象错误

python - 使用 Python 解析格式化的 JSON