【问题标题】:jQuery concatenate variables if both have a value?如果两者都有值,jQuery连接变量?
【发布时间】:2018-08-25 04:25:11
【问题描述】:

我真的希望这不是重复的,虽然肯定有可能,但我只是没有搜索正确的术语。

我正在基于flyingcars version 开发自己的password strength checker

我正在尝试找出一种方法来组合两个变量(仅当两者都存在时)。

这是我得到的:

var thisVal = $('.password_input').val(),
    thisStrength = zxcvbn(thisVal),
    thisMeter = $('.password_strength_meter'),
    thisLabel = $('.password-text'),
    thisSuggestion = $('.password-text-suggest');

thisSuggestion.text(thisStrength.feedback.warning + ". " thisStrength.feedback.suggestions);

如果

最好的方法真的是执行多个 if 语句吗?或者有没有办法将它内联到 .text() 部分?

我正在考虑进一步扩展它,包括破解所需的时间:

thisSuggestion.text(thisStrength.feedback.warning + ". This password could be cracked in: " + thisStrength.crack_times_display['online_no_throttling_10_per_second'] + ". " + thisStrength.feedback.suggestions);

因此希望可以避免使用多个 if 语句。

【问题讨论】:

  • 如果合并两个变量值,检查变量值是否设置的代码在哪里,简单来说空检查在哪里?
  • 为什么不直接使用 HTML5 输入验证?
  • @Ramesh,这就是我想要解决的问题。是否有办法在 .text() 部分执行此操作,或者是否需要在该部分之外执行?
  • @TheIncorrigible1 因为我喜欢 zxcvbn 附带的附加功能,比如建议用户可以采取哪些措施来修复他们的弱密码。我也可能会将它包含在 noscript 中
  • 是的,这是可能的。您可以使用 ternary 运算符来执行此操作。但是如果您问我,我建议您单独检查验证它是您代码的标准。

标签: javascript jquery concatenation zxcvbn


【解决方案1】:

一种快速而简洁的方法是将所有可能包含字符串的变量添加到数组中。然后,您可以过滤掉空白或虚假值,并将剩余的值与您选择的分隔符连接起来。

const a = 'This will be there',
  b = '',
  c = null,
  d = 'So will this';

let result = [a, b, c, d].filter(x => x).join('. ') + '.';

console.log(result);

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多