我有这段代码可以计算行数并返回在 MySQL 表中找到的行数。这是代码,我在其中使用了 underscore.js 的 _.each
进行迭代。
var all_rows = Noder.query('SELECT count(*) as erow from crud ', function(err, the_rows) {
_.each(the_rows, function (corndog) {
var trows = corndog.erow;
console.log("All rows", trows);
});
// var das_rows = trows;
// var total_pages = Math.ceil(das_rows / per_page);
// console.log("Pages",total_pages);
res.view('noder/orm', {
layout: 'layout',
js:the_rows,
post:results,
title: 'This is the hi page title. Gandalf The great.'
});
});
我想使用trows
来计算要为我的分页代码创建的页面数。但是,我无法访问变量 trows
。
这是 console.log(the_rows);
的输出
[ RowDataPacket { erow: 12 } ]
有没有其他方法可以使 trows
可用于我的其余代码?
最佳答案
问题是 var trows
只存在于迭代器内部,因为 function
创建了自己的范围来包含变量。
function (corndog) {
var trows = corndog.erow;
console.log("All rows",trows);
} // `trows` is removed from existence at this point
console.log(trows); // ReferencError
但是,函数
确实可以访问周围作用域中的变量。因此,您可以在函数外部声明 trows
,然后在内部对其进行赋值。
var trows;
_.each(the_rows, function (corndog) {
trows = corndog.erow; // note removal of `var`
console.log("All rows",trows);
});
console.log(trows); // 12
不过,当您只需要一个值时,_.each()
并不是必需的。您可以访问集合的特定索引并链接到您所追求的属性上:
var trows = the_rows[0].erow;
如果担心 the_rows
为空,您可以 test for that为了避免 undefined
的错误:
var trows = the_rows.length ? the_rows[0].erow : null;
旁注:一定要始终测试 err
。如果发生这种情况,the_rows
可能会是 null
或 undefined
。
关于javascript - 替换函数中的 _.each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34466205/