未定义forEach TypeError:undefined不是函数
我正在把一个nodejs应用程序放在一起,从我经常访问的网站上获取我的奖项,并且遇到了一个让它工作的问题。 我试图找出如何将主题variables作为parameter passing给我的profile.get函数。
试图以下:
users.forEach(profile.get(topic));
结果:
users.forEach(profile.get(topic)); ^ TypeError: undefined is not a function at Array.forEach (native)
app.js
var profile = require("./profile.js"); var topic = process.argv.slice(2,3); var users = process.argv.slice(3); users.forEach(profile.get);
profile.js
function get(username, topic) { //Connect to API URL (http://url.com/username.json) var request = https.get("https://url.com/" + username + ".json", function(response) { var body = ""; //Read the data response.on('data', function(chunk) { body += chunk; }); response.on('end', function() { if (response.statusCode == 200) { try { //Parse the data var profile = JSON.parse(body); //Print the data printer.printMessage(username, profile.badges.length, profile.points.topic, topic); } catch(error) { //Parse Error printer.printError(error); } } else { //Status Code Error printer.printError({message: "There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"}); } }); }); //Connection Error request.on('error', printer.printError); }
更新:
的console.log(用户);
返回['myuserrname','secondusernamehere']
如果users
包含要传递给.get()
函数的用户名,那么你的循环如下所示:
users.forEach(function(username) { profile.get(username, topic); });
.forEach()
方法调用你的callback函数,连续地传递数组中的每个值。 如果这些值是用户名,那么每个callback函数都会给你一个用户名。 假设topic
值是在您发布的代码之外定义的东西,它也将在callback内部可见。
在您的尝试中,您直接调用profile.get()
并将其返回值传递给.forEach()
。 该函数没有返回值,所以这就是为什么.forEach()
抛出exception – 你传递的callback值是undefined
。
在您之前关于此代码的问题中 ,您正在使用仅带有一个参数的那个.get()
函数的版本。 正因为如此,使用
users.forEach(profile.get);
工作得很好,因为您将.get()
函数的引用传递给.forEach()
,所以它工作。 但是在这个代码中:
users.forEach(profile.get(topic));
那个profile.get(topic)
是对这个函数的调用 。 这是造成这个问题的原因。 在JavaScript中,解决类似问题的方法(至less,最简单的方法)是在这个答案的顶部引入包装函数。 现在, .forEach()
很高兴,因为你传递了一个函数来调用,而profile.get()
很高兴,因为你传递了它所期望的两个参数。