如何在nodejs中输出'i'
How to output 'i' in nodejs
我目前正在尝试查看 'steam ids' 是否有人;因为我想得到一个不错的..所以我想我会花 5 分钟来制作这个小脚本,但无论我尝试什么它都不会输出 "list"
const request = require("request");
var fs = require('fs');
var list = fs.readFileSync("list.txt", "utf-8").split("\n");
for(i of list){
request({
method: "GET",
url: "https://steamcommunity.com/id/" + i,
}, (error, response, body) => {
if(body.match("The specified profile could not be found.")) {
console.log(i + "not taken");
} else {
console.log(i + "taken");
}
})
}
脚本有效;并知道哪个 ID 未被盗用,哪个被盗用……但问题是我看不到未被盗用的 ID - 如果有人能帮助我,我将不胜感激!
这是一个标准问题,您的变量范围发生了变化,并且范围不是您所期望的范围。
const request = require("request");
var fs = require('fs');
var list = fs.readFileSync("list.txt", "utf-8").split("\n");
var i;
for (i of list) {
(function(id) {
request({
method: "GET",
url: "https://steamcommunity.com/id/" + id,
}, (error, response, body) => {
if (body.match("The specified profile could not be found.")) {
console.log(id + "not taken");
} else {
console.log(id + "taken");
}
})
})(i);
}
由于外部(for
循环)和请求的处理程序之间没有作用域差异,变量 i
将在请求结束时发生变化。我在您的代码中添加了一个闭包,以确保此变量的副本存在于词法范围内,因此您的处理程序知道它查询的 ID。
有更简洁的方法可以做到这一点。特别是,您可以使用迭代器来简化它。
我目前正在尝试查看 'steam ids' 是否有人;因为我想得到一个不错的..所以我想我会花 5 分钟来制作这个小脚本,但无论我尝试什么它都不会输出 "list"
const request = require("request");
var fs = require('fs');
var list = fs.readFileSync("list.txt", "utf-8").split("\n");
for(i of list){
request({
method: "GET",
url: "https://steamcommunity.com/id/" + i,
}, (error, response, body) => {
if(body.match("The specified profile could not be found.")) {
console.log(i + "not taken");
} else {
console.log(i + "taken");
}
})
}
脚本有效;并知道哪个 ID 未被盗用,哪个被盗用……但问题是我看不到未被盗用的 ID - 如果有人能帮助我,我将不胜感激!
这是一个标准问题,您的变量范围发生了变化,并且范围不是您所期望的范围。
const request = require("request");
var fs = require('fs');
var list = fs.readFileSync("list.txt", "utf-8").split("\n");
var i;
for (i of list) {
(function(id) {
request({
method: "GET",
url: "https://steamcommunity.com/id/" + id,
}, (error, response, body) => {
if (body.match("The specified profile could not be found.")) {
console.log(id + "not taken");
} else {
console.log(id + "taken");
}
})
})(i);
}
由于外部(for
循环)和请求的处理程序之间没有作用域差异,变量 i
将在请求结束时发生变化。我在您的代码中添加了一个闭包,以确保此变量的副本存在于词法范围内,因此您的处理程序知道它查询的 ID。
有更简洁的方法可以做到这一点。特别是,您可以使用迭代器来简化它。