是否可以通过某种方式将项目推送到JavaScript对象内部的数组中
这是我的代码:
function test() {
this.array = [];
this.addItem = function() {
this.array.push("someString");
}
this.removeItem = function() {
this.array.remove(0);
}}
答案 0 :(得分:1)
看看这段代码-
var obj = {
numbers: [1, 2, 3, 4]
}
obj.numbers.push(5)
console.log(obj.numbers)
答案 1 :(得分:1)
如果要使用对象,可以使用 Javascript ES6
class Test {
constructor() {
this.array = [];
}
addItem(item) {
this.array.push(item);
}
removeItem() {
this.array.splice(0, 1);
}
removeItemByIndex(index) {
this.array.splice(index, 1);
}
}
const test = new Test();
test.addItem('Some Item');
test.addItem('Some Item 2');
console.log(test.array);
test.removeItem();
console.log(test.array);