我正在从 Stoyan Stefanov 的书中学习 JS OOP。我在第 4 章的练习 4 中遇到了问题:
Imagine the String()constructor didn't exist. Create a constructor function MyString()that acts like String()as closely as possible. You're not allowed to use any built-in string methods or properties, and remember that String()doesn't exist. You can use this code to test your constructor:
下面是我尝试创建类似 String split() 的方法。你能指导我如何让它发挥作用吗?
function MineString(string){
this.lengthS = string.length;
//this[1] = "test";
for(var i = 0; i < string.length;i++){
this[i] = string.charAt(i);
}
this.toString = function(){
return string;
}
this.split = function(char){
var splitedArray = [];
var foundedChar = [];
var string2 = [];
for (var i = 0; i < this.lengthS ; i++){
foundedChar.push(string[i].indexOf(char));
}
for (var j = 0; j < foundedChar.length; j++){
if(foundedChar[j] === -1){
//splitedArray[0] += string.charAt(j);
//splitedArray[j] = string.charAt(j);
string2 += string.charAt(j);
//splitedArray.push(string2);
splitedArray[foundedChar.length] = string2;
}else if (foundedChar[j] === 0){
//splitedArray.push(string.charAt(j));
}
}
return splitedArray;
}
}
var text = new MineString("hello");
text.split("e");
所以text.split("e");应显示如下内容:
var text = new MineString("hello");
text.split("e");
["h","llo"]
最佳答案
你的 split 方法看起来有点过于复杂。我简化了它并重写了类的其他部分,以便它们遵守不使用字符串方法的任务。请参阅jsfiddle或下面的代码。
新的 JS 代码:
function MineString(str){
this.str = str;
this.addChar = function(c) {
this.str += c;
}
this.length = function() {
return this.str.length;
}
this.toString = function(){
return this.str;
}
this.split = function(char){
var out = [],
current = new MineString(""),
addCurrent = function() {
if (current.length() > 0) {
out.push(current.toString());
current = new MineString("");
}
};
for (i = 0; i < this.str.length; i++) {
if (this.str[i] == char) {
addCurrent();
} else {
current.addChar(this.str[i]);
}
}
addCurrent();
return out;
}
}
var text = new MineString("hello");
console.log(text.split("e"));
输出:
["h", "llo"]
关于javascript - 模拟 Javascript 面向对象编程 Stoyan Stefanov 书中的字符串 split(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29570349/