Javascript var提升问题 [英] Javascript var hoisting issue
问题描述
我有一个非常简单的Javascript函数,可以访问MS SQL服务器并返回一些记录。有一个单元格,我想只在它是唯一的时候显示在顶部表格行中。
我相信我的问题是var hoisting,因为我在while循环中分配的变量不起作用,因为该值不是从最后一个记录中进行比较的。这是代码
I have a very simple Javascript function that hits a MS SQL server and returns some records back. There is a cell that i want to only display in the top table row when it is unique. I believe my problem is var hoisting because the variable that i assign within the while loop does not work because the value is not carried from the last records to compare. Here is the code
function searchIndex()
{
var termcounter = "";
flyoutHTML = '<table>';
var adOpenDynamic = 2
var adLockOptimistic = 3
var conn = new ActiveXObject("ADODB.Connection");
var connectionstring = "Provider=SQLOLEDB;Server=XXXXXXXX;INTEGRATED SECURITY=SSPI;DATABASE=YYYYYYYYYY;"
conn.Open(connectionstring)
var rs = new ActiveXObject("ADODB.Recordset")
rs.Open("SELECT field1, field2, field4, field4, field5 FROM dbo.table;", conn)
if (rs.eof)
{
flyoutHTML += '<tr><td align="center">No Records Found!</td></tr>';
}
else
{
while(!rs.eof)
{
if (termcounter != rs(0))
{
var termcounter = rs(0);
flyoutHTML += '<tr>';
flyoutHTML += '<td colspan="3">' + rs(0) + '</td>';
flyoutHTML += '</tr>';
}
flyoutHTML += '<tr>';
flyoutHTML += '<td>' + rs(1) + '</td><td>' + rs(2) + '</td><td>' + rs(3) + '</td>';
flyoutHTML += '</tr>';
rs.movenext
}
rs.close
conn.close
flyoutHTML += '</table>';
}
推荐答案
拿走var关闭 var termcounter = rs(0);
你可能正确地提升 - JavaScript没有块范围,因此两次声明termcounter它都在同一范围内。这是一个非常常见的错误,因为JavaScript看起来像具有块范围的基于C的语言。
You're probably right about hoisting--JavaScript doesn't have block scope, so both times you declare termcounter it's in the same scope. This is a very common mistake, since JavaScript looks like C-based languages which have block scope.
声明条件或循环块中的var等同于声明它块的功能的开头,范围方式。
Declaring a var in a conditional or looping block is equivalent to declaring it at the beginning of the function that block is in, scope-wise.
如果你总是将var声明放在函数的顶部,你将失去更少的头发 - 永远不会在条件或循环块中。 查看Crockford 。您可以使用 JSLint 向您发出警告。 (哦,顺便说一句,你丢失了大量的分号 - JSLint会伤害你的感情。)
You'll lose less hair if you always place your var declarations at the top of functions--never in conditional or loop blocks. See Crockford. You can use JSLint to warn you. (Oh, by the way, you're missing a ton of semicolons--JSLint will hurt your feelings.)
那你为什么要重新声明呢?删除第二个var并进行分配。
So why are you redeclaring it? Drop the second "var" and just do the assignment.
微软的东西对我来说很陌生,但我发现rs(0)语法莫名其妙。是一个对象吗?或者是否有某种神奇使它成为一个函数(你从来不知道JS)? 我做了一些谷歌搜索,我想知道你是否需要成为使用rs.fields(0)或rs.fields(0).name或rs.fields(0).value或其他东西。
The Microsoft stuff is alien to me, but I find the rs(0) syntax baffling. Is rs an object? Or is there some kind of magic that makes it into a function as well (you never know with JS)? I did some Googling and I wonder if you need to be using rs.fields(0) or rs.fields(0).name or rs.fields(0).value or something.
这篇关于Javascript var提升问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!