String.prototype.mySlice = function(start, end) {
if (end == undefined){
end = str.length;
}
if (start < 0) {
start = this.length + start;
end = this.length + end;
}
let str2 = [], x = 0;
for (let y = 0; y < str.length; y++){
if (y >= start && y < end){
str2[x] = str[y];
x++;
}
}
return str2.join("");
}
let str = 'hello world';
console.log(str.mySlice(1));
console.log(str.mySlice(1,5));
console.log(str.mySlice(-4,-1));
2、通过原型方式,自定义一方法,实现功能类似substring
substring(起始,结束) 参数均为正数
String.prototype.mySubstring = function(start, end) {
if (end == undefined){
end = str.length;
}
let str2 = [], x = 0;
for (let y = 0; y < str.length; y++){
if (y >= start && y < end){
str2[x] = str[y];
x++;
}
}
return str2.join("");
}
let str = 'hello world';
console.log(str.mySubstring(1));
console.log(str.mySubstring(1,5));
3、通过原型方式,自定义一方法,实现字符串加密、解密(ASC码)
String.prototype.myPasswd = function () {
let len = str.length;
let num = "";
for (let i = 0; i < str.length; i++) {
num += str.charCodeAt(i);
}
return num;
}
let str = 'hello';
console.log(str.myPasswd());
String.prototype.myPasswd2 = function () {
let num = [];
let num2 = this.split('');
for (let i = 0; i < num2.length; i++) {
num.push(String.fromCharCode(num[i]));
}
return num;
}
let str = '104, 104';
console.log(str.myPasswd2());
4、通过原型方式,自定义一方法,实现数字保留N位小数(四舍五入)
String.prototype.mySave = function(number, n){
if (n <= 0) {
return Math.round(number);
}
number = Math.round( number * Math.pow(10, n)) / Math.pow(10, n);
return number;
}
console.log(String.prototype.mySave(12.239, 2));
5、重构选择题6,实现打印:undefinede 0 1 2 3 4 …
function fun(n, o) {
console.log(o)
return {
fun: function (m) {
return fun(m, n);
}
};
}
a = fun(0);
b = a.fun(1);
c = b.fun(2);
d = c.fun(3);
e = d.fun(4);
6、通过原型方式(Array),自定义一方法,实现m的n次幂
Array.prototype.myArr = function(m, n) {
let val =1;
for(let i = 1; i <= n; i++){
val *= m;
}
return val;
}
console.log(Array.prototype.myArr(2, 5));
7、通过原型方式,自定义一方法,实现:
“张三” -> “张*” “张大山” -> “张山" “欧阳小鹭” -> "欧鹭”
String.prototype.myName = function(name){
let newStr = '';
if(name.length == 2) {
newStr = name.substr(0,1) + '*';
} else if (name.length > 2) {
let char = '';
let len = name.length - 2
for (let x = 0; x < len; x++) {
char += '*';
}
newStr = name.substr(0,1) + char + name.substr(-1,1);
} else {
newStr = name;
}
return newStr;
}
console.log(name.myName('张三'));
console.log(name.myName('张大山'));
console.log(name.myName('欧阳小鹭'));