简体   繁体   English

JavaScript编辑对象内部的数组

[英]JavaScript edit Array inside Object

Is it somehow possible to push items to an array inside of a JavaScript object 是否可以将项目推送到JavaScript对象内部的数组

Here my code: 这是我的代码:

function test() {
this.array = [];

this.addItem = function() {
    this.array.push("someString");
}

this.removeItem = function() {
    this.array.remove(0);
}}

Look at this code- 看这段代码-

 var obj = { numbers: [1, 2, 3, 4] } obj.numbers.push(5) console.log(obj.numbers) 

If you want to work with Objects, you can use Javascript ES6 如果要使用对象,则可以使用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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM