3 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
// 這里定義一個(gè)全局的index標(biāo)識上次添加的id的位置
let index = 0;
let arr = [
{id:1,text:"生活不只眼前的茍且"},
{id:2,text:"還有詩"},
{id:3,text:"和遠(yuǎn)方"}
];
let arrLength = arr.length;
let items = [];
document.getElementById("add").onclick = function(){
// 防止數(shù)組下標(biāo)溢出
if (index <= arrLength - 1) {
items.push(arr[index]);
// 添加完成之后下標(biāo)后移
index++;
}
console.log(items);
}

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
可以先確定這個(gè)id,然后做一個(gè)比較
var id = ''
$("#add").click(function(){
for(var i = 0;i<arr.length;i++){
if (id === arr[i].id) {
items.push(arr[i]);
}
}
})

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
閉包+立即執(zhí)行函數(shù)實(shí)現(xiàn):
$('#add').click(
(function() {
let count = 0;
return function() {
items.push(arr[count++]);
};
})()
);
添加回答
舉報(bào)