【发布时间】:2015-10-12 19:25:40
【问题描述】:
我正在尝试在 nodejs 上开发一个随机类别 ID 生成器函数。首先,我从我的数据库中接收所有现有的类别 ID 并将它们推送到一个数组中,然后我生成一个随机整数(在边界之间),并将随机数与我的 cat id 数组进行比较。我使用 indexof() 函数进行比较,但它总是返回 true;可能是什么问题。这是我的代码;
var random = require("random-js")
var selectCategoryID = "SELECT id from category.category";
var catIdresult = client.querySync(selectCategoryID);
var catIdArray = [];
catIdresult.forEach(function (row) {
var catId = row.id;
catIdArray.push(catId);
});
var randomNum = new random()
var K = randomNum.integer(16777000, 16777999);
if(catIdArray.indexOf(K)){
console.log("Error, the id is : " + K);
}
else {console.log("Success, the id is : " + K)}
【问题讨论】:
-
应该是
if(catIdArray.indexOf(K) < 0) -
不与下面提到的结果相同