结合'var'语句

时间:2014-11-17 19:35:39

标签: javascript jslint

JSLint告诉我Combine this with the previous 'var' statement会遇到问题,但我不确定我是如何使用我的代码正确执行的:

var len = results.rows.length, i;
//loop around each record in the database
for (i = 0; i < len; i++) {
    var singleRecord = results.rows.item(i);

    //create list
     var individualRecord = '';
     individualRecord = '<li><a href="#info" id="anIndividualRecord" data-key="' + individualRecord.id + '" >';

它告诉我要将三个var语句合并在一起,但如果有人可以告诉我如何在不产生更多问题的情况下这样做,那将非常感激。

4 个答案:

答案 0 :(得分:2)

在您的最高var声明

中完成所有操作
var len = results.rows.length, i, inidividualRecord, singleRecord;

for(i=0; i< len; i++) {
  singleRecord = results.rows.item(i);

  individualRecord = '<li><a href="#info" id="anIndividualRecord" data-key="' + singleRecord.id + '" >';
}

答案 1 :(得分:2)

组合来自同一范围的多个var就像从一行中删除var语句并将相关标识符附加到同一范围内的其他var一样简单。

var len = results.rows.length,
    i,
    individualRecord; // added identifier, only need one var'd copy of each identifier

//loop around each record in the database
for (i = 0; i < len; i++) {
    individualRecord = results.rows.item(i); // removed var

    //create list
     individualRecord = ''; // removed var
     individualRecord = '<li><a href="#info" id="anIndividualRecord" data-key="' + individualRecord.id + '" >';

答案 2 :(得分:1)

在这种情况下,您无法重新声明变量:individualRecord 并且jsHint可能会抛出你需要在JavaScript中组合你的var declarations到期吊装。

(function () {
  var len = results.rows.length,
    i,
    individualRecord,
    singleRecord;

  for (i = 0; i < len; i++) {
    singleRecord = results.rows.item(i);
    individualRecord = '';
    individualRecord = '<li><a href="#info" id="anIndividualRecord" data-key="' + individualRecord.id + '" >';
  }
}());

答案 3 :(得分:0)

变量基本上可以做三件事:DeclarationInitializationAssignment。关键字var表示变量声明,whis仅对每个变量执行一次。这通常与Initialization一起设置变量的初始值。正确的方法是:

// add individualRecord here
var len = results.rows.length, i,singleRecord, individualRecord;

//loop around each record in the database
for (i = 0; i < len; i++) {
    // omit the "var" here
    singleRecord = results.rows.item(i);

    // and here as well
     individualRecord = '';

Javascript做了一些叫做"hoisting"的讨厌的东西,所以知道细微差别很重要。