gpt4 book ai didi

javascript - 未知的 JavaScript 语法

转载 作者:行者123 更新时间:2023-12-01 02:57:38 24 4
gpt4 key购买 nike

所以我是 javascript 的新手,我遇到了这个:

 /**
* Replaces %1, %2 and so on in the string to the arguments.
*
* @method String.prototype.format
* @param {Any} ...args The objects to format
* @return {String} A formatted string
*/
String.prototype.format = function() {
var args = arguments;
return this.replace(/%([0-9]+)/g, function(s, n) {
return args[Number(n) - 1];
});
};

你们能帮我弄清楚这几件事的含义吗:)

首先,我不明白“var args = argument;”中的“arguments”是什么意思。应该是,它是什么类型?我不明白它在这里做什么。其次,“/%([0-9]+)/g”的作用是什么?我无法理解这些。第三,该功能如何实现其所说的功能?我对这一切感到困惑。谢谢!

最佳答案

arguments object 是为每个函数调用创建的特殊对象。在 documentation 中了解更多相关信息:

The arguments object is a local variable available within all (non-arrow) functions. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0.

/%([0-9]+)/gregular expression文字。这些文字通过其 / 来区分。分隔符,就像引号表示字符串文字一样。正则表达式本身就是一种语言,也可以在其他语言环境中使用。它们用于查找字符串中的模式,因此是比 .indexOf 更强大的搜索方式。可以提供。在 documentation 中阅读相关内容.

以下是该正则表达式的分割:

  • / : 分隔符:这不是正则表达式的一部分,只是告诉Javascript这是一个正则表达式文字

  • % : 将匹配字面百分比符号。

  • ( ) :捕获组。与这些括号内的模式匹配的任何内容都可以稍后作为单独的字符串值检索(在本例中,在传递给 replace 的回调函数中)

  • [ ] : 字符的集合。搜索字符串中的下一个字符(百分比符号之后)应该是其中之一。

  • [0-9] :一个数字。

  • + :先前的模式可以出现多次,但至少出现一次。因此,在这种情况下,应该至少有一位数字,但也允许更多。

  • g :这是正则表达式的修饰符,它将使其匹配模式的所有出现,而不仅仅是第一个。

也许还提到this ,这是 format 所在的字符串方法被调用。具体是哪个字符串,只有在调用函数时才知道。

replace方法可以将正则表达式作为其第一个参数,在这种情况下,它会查找以百分比符号开头,后跟无符号整数的模式。

在此代码中 replace方法还得到 callback function passed to it 。对于字符串中找到的每个匹配项,都会调用此函数。该字符串返回的值将用作找到的内容的替换字符串。所以这意味着所有这些 %nn子字符串将被替换为 arguments 中的内容目的。

在这种情况下,回调函数使用两个参数调用:第一个参数是匹配的字符串,例如 %1 ,第二个是第一个捕获组(请参阅正则表达式中的括号):这与第一个参数相同,但没有 % .

Number函数会将数字字符串转换为数字。如%1应该引用第一个参数,并且第一个参数的索引为 0,必须从该数字中减去 1 才能获得 args 中的正确索引。类似数组的对象。

调试

你可以放置一些console.log()该代码中的语句可以更好地掌握正在发生的事情,例如这样:

String.prototype.format = function() {
var args = arguments;
console.log('arguments:', JSON.stringify(args));
console.log('string to deal with: ' + this);
return this.replace(/%([0-9]+)/g, function(s, n) {
console.log('found:', s, 'with digit(s)', n);
console.log('replacing that with argument at index:', (Number(n) - 1), 'which is', args[Number(n) - 1]);
return args[Number(n) - 1];
});
};

// Run the above method
var result = "My name is %1 and I am %2 years old.".format("Maria", 24);
console.log('final result:', result);

关于javascript - 未知的 JavaScript 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46625451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com