如何在Javascript对象中自动拆分文本?

时间:2011-04-15 15:53:59

标签: javascript function object split

我希望有一个对象接受带有“dog:cat:whale”等分隔符的输入字符串,并希望“splittedText”中的属性成为分割后输入对象的数组"spittedText[0] = dog, spittedText[1] = cat, spittedText[2] = whale".

以下是我想要完成的通用伪代码,但不起作用......

function someObject(input) {
    this.splittedText=input.split(':');
}

为了测试,我应该能够做到这一点:

theObject = new someObject("dog:cat:whale");
alert(someObject(theObject.splittedText[0])); // should print out dog

我做错了什么?我该如何做到这一点?

2 个答案:

答案 0 :(得分:1)

你不应该再次调用该函数。

alert(theObject.splittedText[0]);

答案 1 :(得分:0)

这对我有用:

var someObj = new SomeObject("dog:cat:whale");

function SomeObject(str){
    this.splittedText = str.split(':');
}

alert(someObj.splittedText);