简体   繁体   中英

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

I'm using Node.js to make an app with electron. In my code, I have something like this:

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

Where element is a string structured similarly to this:

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:

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

The program is supposed to pass the id to another function:

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:

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.

The match functions returns an array of string that match with the regex. 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. Check how you fill the items array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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