使用名称/值

时间:2016-03-22 16:09:34

标签: javascript arrays angularjs json

我知道如何从json数组中删除一个项目,但是在添加时我似乎无法使其工作。

数组:

var users = [ 
{name: 'james', id: '1'}
]

想要添加,所以它变为:

  var users = [ 
  {name: 'james', id: '1'},
  {name: 'thomas', id: '2'}
  ]

以下是删除数组的代码:

 Array.prototype.removeValue = function(name, value){
       var array = $.map(this, function(v,i){
       return v[name] === value ? null : v;
    });
    this.length = 0; //clear original array
    this.push.apply(this, array); //push all elements except the one we want to delete
    } 

   removeValue('name', value);
//space removed

我需要做些什么更改来反向向数组中添加值?

2 个答案:

答案 0 :(得分:0)

使用Array.prototype.push()

var sports = ["plongée", "baseball"];
var total = sports.push("football", "tennis");

console.log(sports); // ["plongée", "baseball", "football", "tennis"]
console.log(total);  // 4

答案 1 :(得分:0)

我认为一个更合适的函数是filter而不是map

 Array.prototype.removeValue = function(name, value){
    var array = $.filter(this, function(v,i){
       return v[name] !== value;
    });
    this.length = 0; //clear original array
    this.push.apply(this, array); //push all elements except the one we want to delete
 }

我只是假设长度并推动黑客工作,因为我自己从未使用它们。

相关问题