单击按钮后如何将数据从数组插入数组

时间:2018-12-30 16:37:44

标签: javascript arrays

单击按钮后,我需要将数组触点中的数据一一插入到数组数据中。单击按钮后插入联系人[0],再次单击不带联系人[0]的联系人[1],然后单击下一步[2] ...

<button id="submit-btn" onclick="myFunc()">Search</button>

  const contacts = ['Chriss:23232','Sarah:345232','Bill:893246','Mary:254366',
                    'Dianne:2434356','Amy:2356546','Andreu:23546457'];


    var data = [];
    function myFunc(){
            //var res = contacts.filter(f => !data.includes(f));

        for ( let x = 0; x < contacts.length; x++ ){
            data.push(contacts[x]);
        }
    }

这将保存整个联系人。

2 个答案:

答案 0 :(得分:3)

使用shift并确保点击次数不会超出数组的长度。如果您不添加校验而超过数组长度后,它将继续添加undefined

您可以使用全局变量作为索引跟踪器,并保持更新,每次单击按钮并在数据数组中推送值时。但是在JS世界中,通常认为使用全局变量是一种反模式。

const contacts = 
['Chriss:23232','Sarah:345232','Bill:893246','Mary:254366','Dianne:2434356','Amy:2356546','Andreu:23546457'];

    var data = [];
function myFunc(){
  if(contacts &&contacts.length > 0)
  {
    data.push(contacts.shift());
    console.log(data)
  } else {
    console.log('No more contacts in your list')
  }
}
<button id="submit-btn" onclick="myFunc()">Search</button>

答案 1 :(得分:2)

只需使用全局计数器值,然后在函数中将其递增并推入数组即可:

 

const contacts = ['Chriss:23232','Sarah:345232','Bill:893246','Mary:254366','Dianne:2434356','Amy:2356546','Andreu:23546457'];
var counter = 0;
var data = [];
function myFunc() {
    if (!(counter++ > contacts.length)) {
        data.push(contacts[counter]);
        counter++;
        console.log(data);
    } else {
        alert("No more contacts left!");
    }
}
 

<button id="search-btn" onclick="myFunc()">Search</button>