【问题标题】:Recursive function for finding available indexes returning 0用于查找返回 0 的可用索引的递归函数
【发布时间】:2021-01-31 12:46:21
【问题描述】:

基本上,我将键值对输入到表单中。

最初,我只是将它们定义为inputname['key'],并附加了值。

我意识到需要对第三个参数进行编码,因为数组中具有相同键的项会覆盖具有不同值的其他输入。

我写了一个非常简单的(或者我认为是这样的)递归函数来判断给定索引是否可用。下面是

addString: function(str) {
    var maxInd = this.checkCurrentReturnIndex(str, 0);
    return 'friends['+maxInd+str+']';
},
checkCurrentReturnIndex(userid, currentInd) {
   // Recursive function to determine proper, unused index
   if(!$('input[name="friends['+currentInd+userid+'"]').length) {
       return currentInd;
   } else {
       return this.checkCurrentReturnIndex(userid, (currentInd + 1));
   }
},

这是在 Vue 方法中,尽管上面的代码有一些不同的变化,但我无法让它输出任何不是 0 的东西。

【问题讨论】:

  • 这表明 $('input[name="friends['+currentInd+userid+'"]').length 始终为 0 - 没有任何提示您的网页,问题是没有输入具有像 name="friends[0xxx]" 这样的属性,其中 xxx 是 userid
  • 顺便说一句,每当我看到 vue.js 和 jquery 一起使用时,我都认为你做错了——但这不仅仅是我的观点
  • 你能提供更多的背景信息吗?我会说最初你可能会混淆你的表示层和数据层,或者至少应该在这里产生更多的分离。可能有更简单的处理方式。

标签: javascript jquery vue.js recursion


【解决方案1】:

看起来您可能只是错误地构建了您的 jQuery 选择器。

根据您的代码示例,我假设您的 HTML 看起来像这样,其中 userids 是 user01user02 等,前缀为该用户的唯一索引:

<input type="text" name="friends[0user01]">
<input type="text" name="friends[1user01]">
<input type="text" name="friends[2user01]">
<input type="text" name="friends[0user02]">
<input type="text" name="friends[1user02]">
<input type="text" name="friends[2user02]">
<input type="text" name="friends[3user02]">  

您的选择器当前如下所示:

$('input[name="friends['+currentInd+userid+'"]')
//                        closing " is here ^

对于0 中的currentInduser01 中的userid,会变成这样:

$('input[name="friends[0user01"]');
//          closing " is here ^

我怀疑这是不正确的。

如果您像这样将结束 " 移动到结束括号之外:

$('input[name="friends['+currentInd+userid+']"')
//                              move to here ^

选择器将如下所示:

$('input[name="friends[0user01]"')
//           closing " is here ^

这可能会解决您的问题。

Here's a fiddle 似乎只进行了很小的修正——您的递归函数构建正确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 2018-07-15
    • 2014-01-07
    相关资源
    最近更新 更多