给字符串对象定义一个repeat功能。当传入一个整数n时,它会返回重复n次字符串的结果。
2017-12-06 13:50
519 查看
比如console.log("html".repeat(3));会得到htmlhtmlhtml。
知识点解释:JavaScript继承和prototype的知识点。
举例:
这里的另一个要点是,你要知道如何不覆盖可能已经定义的功能。通过测试一下该功能定义之前并不存在:
当你被要求做好JavaScript函数兼容时这种技术特别有用。
运行结果:
知识点解释:JavaScript继承和prototype的知识点。
举例:
String.prototype.repeat = String.prototype.repeat || function (times) { var string = ''; for (var i = 0; i < times; i++) { string += this; // this的值为调用此方法的字符串 } return string; } console.log('html'.repeat(3));
这里的另一个要点是,你要知道如何不覆盖可能已经定义的功能。通过测试一下该功能定义之前并不存在:
String.prototype.repeat = String.prototype.repeat || function(times) {/* code here */};
当你被要求做好JavaScript函数兼容时这种技术特别有用。
运行结果:
相关文章推荐
- 函数功能:传入一个数组,返回数组中第二大数。已知数组中的对象都是数字构成的字符串,且任意两元素不相等。 如传入:@[@"1",@"2",@"3",@"4"],返回@"3"
- 1.编写一个名称为MyClass一个类,在该类中编写一个方法,名称为CountChar,返回值为整型,参数两个,第一个参数可以是字符串、整数、单精度、双精度,第二个参数为字符,方法功能返回第二个参数在
- 【C语言】为下面的函数原型编写函数定义: int ascii_to_integer(char *str); 这个字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。
- 基本字符串压缩 利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。
- 继续在该类中编写一下方法,名称为Reconvert,参数一个,但可以是字符串、整数、单精度、双精度,方法功能返回参数的逆序。如Reconvert(6221982)返回值为2891226。
- Hibernate查询,返回new对象(注意这个新定义的类要有构造函数),使用sql带条件分页查询并且把结果显示到一个对象的集里面的解决方案
- C#--第六周实验--任务2--继续在Class类里编写一个方法,名称为Reconvert,参数一个,但可以是字符串、整数、单精度、双精度,方法功能返回参数的逆序
- c#--编写一个名称为MyClass一个类,在该类中编写一个方法,名称为CountChar,返回值为整型,参数两个,第一个参数可以是字符串、整数、单精度、双精度,第二个参数为字符,方法功能返回第二个参
- Hibernate查询,返回new对象(注意这个新定义的类要有构造函数),使用sql带条件分页查询并且把结果显示到一个对象的集里面的解决方案
- C#--2.继续在该类中编写一下方法,名称为Reconvert,参数一个,但可以是字符串、整数、单精度、双精度,方法功能返回参数的逆序。
- 利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。
- indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回 -1
- 为下面的函数原型编写函数定义: int ascii_to_integer(char *str); 这个字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。如果字符串参数
- 给定一个整数(字符串也适用)序列,重新排列,得到最大的结果,比如31,3,35,7,9根据排列后得到组合 9735331,返回的是string类型
- 定义一个字符串类DelSameStr,从左到右对字符串中每个字符删除其后所有相同的字符,只留下第一次出现的那一个。例如,若字符串为”cocoon”,删除重复出现的字符后,其结果是字符串”con”
- 利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。 给定一个stri
- 利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。
- PHP 为你提供一个叫__toString() 的函数,你可以用它来返回表示对象的字符串信息,而且一旦定义它,打印命令将调用它并打印出返回的字符串。
- //1、有一个字符串开头或结尾含有n个空格(” abcdefgdddd ”),欲去掉前后空格,返回一个新字符串。 //要求1:请自己定义一个接口(函数),并实现功能;70分 //要求2:编写
- 【c语言】为下面的函数原型编写函数定义,这个字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。