【问题标题】:Can I access directly to the second value of an array after .split()?我可以在 .split() 之后直接访问数组的第二个值吗?
【发布时间】:2011-09-12 23:33:35
【问题描述】:

我有这个代码:

var tmp=$(this).attr('id').split("_");

我想在 tmp 上存储拆分后的第二个值。所以如果 $(this).attr('id') = "hello_marco" 我想在 tmp 中存储值 marco,而不是数组。

当然,我想直接在一行代码中完成,而无需先存储数组并使用数组[1]访问它。

在 JS/Jquery 上可以吗?

【问题讨论】:

  • 不要使用.attr() 来获取ID。只需执行this.id.split("_")Here's a jsPerf 说明了像这样过度使用 jQuery 的影响。
  • ...实际上在这种情况下差异更大,因为您还必须创建一个 jQuery 对象。 jsPerf test.

标签: javascript jquery


【解决方案1】:
var tmp = $(this).attr('id').split("_")[1];

【讨论】:

  • 在我写答案时,出现了“三个新答案已发布”的通知。
【解决方案2】:
var tmp = $(this).attr('id').split('_')[1];
//                                     ^^^

Split 返回一个数组,所以只需取消对数组的引用。

【讨论】:

    【解决方案3】:

    添加到最后

    var tmp=$(this).attr('id').split("_")[1];
    

    这可能不是最佳做法,但它确实有效

    【讨论】:

    • 这是一个很好的练习。一直都是惯用的。
    【解决方案4】:
    var tmp = $(this).attr('id').split("_")[1];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 2012-06-12
      • 2019-01-26
      • 2015-02-01
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      相关资源
      最近更新 更多