我试图访问数组的一个特定条目。我正在传递一个字符串,我试图根据空格来解析它。有更简单的方法吗?
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‘。
发布于 2013-12-14 22:04:35
试试这个:
var str = "Hello Everyone this is cool isnt it?";
var toAdd = str.split(" ");
发布于 2013-12-14 22:05:32
你的算法有一个缺陷。参见console.log(toAdd2)
的输出
未定义,"Hello",未定义,“每个人”,未定义,未定义,“此”,未定义,“酷”,未定义,未定义,“不是”,未定义,未定义,"it?“
改为:
if( toAdd[ i ] == " ")
{
sub = toAdd.substring( lastIndex , i ).trim();
toAdd2.push(sub);
lastIndex = i;
}
if( i == toAdd.length - 1 )
{
sub = toAdd.substring( lastIndex, toAdd.length).trim();
toAdd2.push(sub);
}
现在它得到了正确的输出:
["Hello", "Everyone", "this", "is", "cool", "isnt", "it?"]
在您对toAdd
中的每个字符进行迭代之前,只更改符合条件的索引。因此,toAdd2
中的大多数元素都是未赋值的,因此是未定义的。您希望使用array.push
向数组添加元素。
https://stackoverflow.com/questions/20591717
复制