我正在尝试访问数组的特定条目。我传入了一个字符串,并且试图基于空格进行解析。有没有更简单的方法可以做到这一点?

var toAdd = "Hello Everyone this is cool isnt it?";
var final = "";
var toAdd2 = [ ];
var sub = "";
var lastIndex = 0;

for( var i = 0; i < toAdd.length; i++ )
{
    if( toAdd[ i ] == " ")
    {
        sub = toAdd.substring( lastIndex , i ).trim();
        toAdd2[ i ] = sub;
        lastIndex = i;
    }

    if( i == toAdd.length - 1 )
    {
        sub = toAdd.substring( lastIndex, toAdd.length).trim();
        toAdd2[ i ] = sub;
    }
}

console.log( toAdd2[ 0 ] );


这总是给我一个错误的说法,
    TypeError:无法读取未定义的属性“ 0”。

最佳答案

尝试这个:

var str = "Hello Everyone this is cool isnt it?";
var toAdd = str.split(" ");

10-07 14:48