Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 循环遍历数组并检索值_Javascript_Jquery - Fatal编程技术网

Javascript 循环遍历数组并检索值

Javascript 循环遍历数组并检索值,javascript,jquery,Javascript,Jquery,我试图循环一个数组,然后循环一个列表 我遇到的问题是,对于每个都会附加整个数组,但我需要做的是将数组的索引(0)添加到第一个li,将索引(1)添加到第二个li,依此类推 代码: // Create our test array. var arrValues = [ "one", "two", "three" ]; // Loop over each value in the array. $.each(arrValues,function( intIndex, objValue ){

我试图循环一个数组,然后循环一个列表

我遇到的问题是,对于每个
  • 都会附加整个数组,但我需要做的是将数组的索引(0)添加到第一个li,将索引(1)添加到第二个li,依此类推

    代码:

    // Create our test array.
    var arrValues = [ "one", "two", "three" ];
    
    // Loop over each value in the array.
    $.each(arrValues,function( intIndex, objValue ){
        $("#list span").each(function() {
            $(this).append(objValue);
        });
    });
    
    电流输出:

    <ul id="list">
            <li>Content 1 here<span>onetwothree</span></li>
            <li>Content 2 here<span>onetwothree</span></li>
            <li>Content 3 here<span>onetwothree</span></li>
        </ul>
    
    • 内容一、三
    • 内容二、三
    • 内容3这里有三个
    所需输出:

    <ul id="list">
            <li>Content 1 here<span>one</span></li>
            <li>Content 2 here<span>two</span></li>
            <li>Content 3 here<span>three</span></li>
        </ul>
    
    • 内容一
    • 内容二
    • 内容三
    感谢您的帮助:)

    只需执行以下操作:

    var arrValues = [ "one", "two", "three" ];
    
    $("#list span").each(function(index) {
        $(this).append(arrValues[index]);
    });
    

    我认为这将是一种更容易实施的方法:

        $("#list span").each(function( intIndex, objValue ){
            $(this).append(arrValues[intIndex]);
        });
    

    您当前遇到的问题是,您正在迭代数组(3次迭代),每次迭代都会循环遍历整个
    s,因此总共有9次迭代。

    我不熟悉您的列表元素;但是如果您可以使用.get(int index)函数,那么您需要保留一个计数并将其用作索引。