Le *_* Qs 3 javascript underscore.js
我有这个片段来计算行数并返回在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.'
});
});
Run Code Online (Sandbox Code Playgroud)
我想用来trows计算为我的分页代码创建的页数.但是,我无法访问变量trows.
这是输出 console.log(the_rows);
[ RowDataPacket { erow: 12 } ]
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以做到这一点,以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
Run Code Online (Sandbox Code Playgroud)
但是,它function确实可以访问周围范围内的变量.因此,您可以trows在函数外部声明,然后将其分配到内部.
var trows;
_.each(the_rows, function (corndog) {
trows = corndog.erow; // note removal of `var`
console.log("All rows",trows);
});
console.log(trows); // 12
Run Code Online (Sandbox Code Playgroud)
但是,_.each()当你只想要一个单一的价值时,并不是真的有必要.您可以访问集合的特定索引并链接到您所追求的属性:
var trows = the_rows[0].erow;
Run Code Online (Sandbox Code Playgroud)
如果担心the_rows空白,您可以测试它以避免错误undefined:
var trows = the_rows.length ? the_rows[0].erow : null;
Run Code Online (Sandbox Code Playgroud)
旁注:一定要经常测试err.如果发生一个,the_rows很可能是null或undefined.