最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - What is the meaning of {0} in JavaScript - Stack Overflow

programmeradmin1浏览0评论

In the code from this answer:

$.validator.addMethod('lessThanEqual', function(value, element, param) {
    return this.optional(element) || parseInt(value) <= parseInt($(param).val());
}, "The value {0} must be less than {1}");

What is the meaning of {0} and {1}? What is the rule of thumb in Javascript to define those parameter replacements?

So based on the ments, I want to further ask in order to pass {0} and {1} here.

What is the syntax I have to use for validation function lessThanEqual.

thank you

In the code from this answer:

$.validator.addMethod('lessThanEqual', function(value, element, param) {
    return this.optional(element) || parseInt(value) <= parseInt($(param).val());
}, "The value {0} must be less than {1}");

What is the meaning of {0} and {1}? What is the rule of thumb in Javascript to define those parameter replacements?

So based on the ments, I want to further ask in order to pass {0} and {1} here.

What is the syntax I have to use for validation function lessThanEqual.

thank you

Share Improve this question edited May 23, 2017 at 11:47 CommunityBot 11 silver badge asked Jul 14, 2010 at 1:48 q0987q0987 36.1k74 gold badges258 silver badges407 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

There isn't a "special" meaning, they're just tokens that the validator plugin replaces when displaying the message, numerically referring to the parameters for the rule.

Specifically, this is happening in the plugin:

message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters);

So {0} refers to the first parameter, {1} the second and so on. Here's that format function as it is in jQuery.validate 1.7:

$.validator.format = function(source, params) {
  if ( arguments.length == 1 ) 
    return function() {
      var args = $.makeArray(arguments);
      args.unshift(source);
      return $.validator.format.apply( this, args );
    };
  if ( arguments.length > 2 && params.constructor != Array  ) {
    params = $.makeArray(arguments).slice(1);
  }
  if ( params.constructor != Array ) {
    params = [ params ];
  }
  $.each(params, function(i, n) {
    source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
  });
  return source;
};

I think it's validator plugin specific templating syntax to bind {0} to the real value and {1} to the "desired" value.

They are placeholders. In the code that uses the validator, {0} and {1} are replaced by actual values.

They have no special meaning, however they are used as format placeholders, for example:

function format(str/*, args*/) {
  var args = Array.prototype.slice.call(arguments, 1);
  return str.replace(/{(\d+)}/g, function (m, i) {
    return args[i];
  });
}

format("{0} {1}!!", "Hello", "world"); // "Hello world!!"
发布评论

评论列表(0)

  1. 暂无评论