我的实际任务是这样的:
Add a new method to String called format which takes in some color, typeface (italic, bold, striked or none), fontsize, and whether to display in upper or lower case.
Using your new formatting method, format the String "Jose lived in San Jose for many years." as blue, italic, size 12, and all uppercase.
使用提供的注释(以及我通过谷歌搜索找到的网站),我唯一能想到的是:
String.prototype.format = function() {
string = string.fontcolor("Blue")
string = string.italics()
string = string.fontsize(12)
string = string.toUpperCase()
}
var string = "Jose lived in San Jose for many years."
document.write(string.format());
最佳答案
首先,该函数不接受任何参数,那么如何让它接受颜色、字体、大小或大小写???
此外,要获取调用函数的字符串,请使用 this
。但是,您无法更改this
,因此您必须使用临时变量并在最后返回
它。
大致如下:
String.prototype.format = function(col,font,size,caps) {
var str = this;
// do stuff to str
return str;
};
我将让您自行决定如何处理 str
。
关于javascript - 无法弄清楚如何向字符串添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10050580/