3 回答

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

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

TA貢獻1804條經驗 獲得超2個贊
閉包+立即執行函數實現:
$('#add').click(
(function() {
let count = 0;
return function() {
items.push(arr[count++]);
};
})()
);
添加回答
舉報