简体   繁体   English

JavaScript调用带有正则表达式匹配数字的函数(int)会导致错误

[英]JavaScript calling function(int) with a regex match for numbers causes errors

I'm using Node.js to make an app with electron. 我正在使用Node.js用电子制作应用程序。 In my code, I have something like this: 在我的代码中,我有这样的东西:

var id = element.match(/(-?\d+)/g);

Where element is a string structured similarly to this: 其中element是一个类似于以下结构的字符串:

The id of this string is 100, ...

I have an array containing objects called items: 我有一个包含称为项目的对象的数组:

var items = [];

The array is populated beforehand. 预先填充数组。 Each item has a function called getId() , which returns its id, which is also a number: 每个项目都有一个名为getId()的函数,该函数返回其ID,该ID也是一个数字:

exports.getId = function() {
    return id;
};

The program is supposed to pass the id to another function: 该程序应该将id传递给另一个函数:

function getItemById(id) {
    for (var item in items) {
        if (items[item].getId() === id) {
            return items[item];
        }
    }

    return null;
}

However, when I try to use getItemById(id) with the id from the string match, I get the following error: 但是,当我尝试将getItemById(id)与字符串匹配的ID一起使用时,出现以下错误:

Uncaught TypeError: items[item].getId is not a function

Which is strange, because when I try to do one of the following, I receive no errors and the program works as it should: 这很奇怪,因为当我尝试执行以下操作之一时,我没有收到任何错误,并且程序按预期运行:

var item = getItemById(100);
var item = getItemById(parseInt("100"));

I need to get the id from the string as a number and pass it to the getItemById(id) function. 我需要从字符串中获取ID作为一个数字,并将其传递给getItemById(id)函数。

The match functions returns an array of string that match with the regex. match函数返回与正则表达式匹配的字符串数组。 Assuming your input string contains only ONE number you should take the first element from the results. 假设输入字符串仅包含一个数字,则应从结果中获取第一个元素。

var element = 'The id of this string is 100, ...';
var id = element.match(/(-?\d+)/g)[0];

EDIT: the error you're getting probably comes from the fact that items[item] is not of the type you expect, therefore no function called getId exists. 编辑:您得到的错误可能是由于items[item]不是您期望的类型,因此不存在名为getId函数。 Check how you fill the items array. 检查如何填充items数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM