访问数组的特定元素

Accesses specific element of array

本文关键字:元素 数组 访问      更新时间:2023-09-26

我正在尝试访问数组的特定条目。我正在传递一个字符串,并试图根据空格对其进行解析。有更简单的方法吗?

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(" ");

您的算法存在缺陷。参见console.log(toAdd2):的输出

[未定义,未定义,尚未定义,未确定,"你好",未定义的,未定义的,未定义,未定义,"Everyone",未定义,未定义,"this",未定义,未定义的,"is",未确定,未定义,未定义,未定义,"酷",未定义,未定义,"不是",未定义,未定义的,"它?"]

更改为:

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向数组中添加元素。