lisa的个人博客

慢慢理解世界,慢慢更新自己

0%

编程题(三)

手动封装filter方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array.prototype.MyFilter = function(fn){
const result = [];
for(let i = 0;i<this.length;i++){
if(fn(this[i],i)){
result.push(this[i]);
}
};
return result;
};

let arrs = [1, 2, 3, 4, 5, 5].MyFilter(function(val, index) {
return val < 3;
});

console.log(arrs); // [1, 2]

实现一个new

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function _new(){
let fn = [].shift.call(arguments);
let obj = Object.create(fn.prototype);
let res = fn.apply(obj,arguments);
return typeof res==='object'?res:obj;
};

//test
function Person(name, age) {
this.name = name || "lisa";
this.age = age || 10;
}
Person.prototype.say = function() {
console.log(`i am ${this.name},今年${this.age}岁`);
};
let person2 = _new(Person, "lida", 18);
person2.say(); // i am lida,今年18岁

给定两个数组找合集

1
2
3
4
5
6
7
8
9
10
11
12
function collection(arr1,arr2){
let res = [];
for(let i = 0;i<arr1.length;i++){
let idx = arr2.indexOf(arr1[i]);
if(idx>-1){
res.push(arr1[i]);
arr2.splice(idx,1);
};
};
return res;
};
collection([1,2,2,1],[1,2,1]); // [1,2,1]

字符串大小写取反

1
2
3
4
5
6
7
function negation(str){
return str.replace(/\w/g,function(m){
return m === m.toLowerCase()?m.toUpperCase():m.toLowerCase();
});
};

negation('aBc'); // "AbC"