JQuery从数组中删除名称/值对

时间:2013-12-26 17:30:57

标签: javascript jquery

我有一个数组,我填充如下。如何从数组中删除元素?

myArray.push( { "name": "one", "value": "1" } );
myArray.push( { "name": "two", "value": "2" } );

更新:我必须从数组中删除特定元素,比如数组中的{“name”:“one”,“value”:“1”}元素。

3 个答案:

答案 0 :(得分:2)

您可以使用jQuery.grep过滤掉要删除的内容

var myArray = [];
myArray.push( { "name": "one", "value": "1" } );
myArray.push( { "name": "two", "value": "2" } );
myArray = jQuery.grep(myArray, function(value) {
  return value.name != "one"; // return only if name isn't "one"
});
console.log(myArray); // now myArray doesn't contain  { "name": "one", "value": "1" }  in the array

FIDDLE

答案 1 :(得分:1)

您可以使用内置函数(链接:splicepopshift):

var a = [1, 2, 3, 4, 5, 6];
a.splice(1, 1); // [2]     a -> [1, 3, 4, 5, 6]
a.splice(1, 2); // [3, 4]  a -> [1, 5, 6]
a.pop();        // 6       a -> [1, 5]
a.shift();      // 1       a -> [5]

或者创建自己的函数来检查一些标准:

// returns the removed element

function removeFirst(array, fn) {
    var i = 0;
    while (i < array.length) {
        if (fn(array[i]) !== true) i++;
        else return array.splice(i, 1)[0];
    }
}

// returns an array containing the removed elements

function removeAll(array, fn) {
    var i = 0, removed = [];
    while (i < array.length) {
        if (fn(array[i]) !== true) i++;
        else removed.push(array.splice(i, 1)[0]);
    }
    return removed;
}

用法示例:

var array = [
    { name: 'one', value: 11 },
    { name: 'one', value: 1 },
    { name: 'two', value: 2 },
    { name: 'three', value: 3 },
    { name: 'four', value: 4 }
];

// removed -> { name: 'one', value: 1 }

var removed = removeFirst(array, function (item) {
    return item.name === 'one' && item.value === 1;
});

// removed -> [{ name: 'two', value: 2 }, { name: 'three', value: 3 }]

var removed = removeAll(array, function (item) {
    return item.name.charAt(0) === 't';
});

// array -> [{ name: 'one', value: 11 }, { name: 'four', value: 4 }]

答案 2 :(得分:-1)

var myArray = [];
myArray.push( { "name": "one", "value": "1" } );
myArray.push( { "name": "two", "value": "2" } );


//console.log(myArray.toSource()); //FF displays output, google chrome gives error

alert(JSON.stringify(myArray));
//output   [{name:"one", value:"1"}, {name:"two", value:"2"}]



var index = myArray[ 'one' ];
myArray.splice(index, 1);

//console.log(myArray.toSource());   //FF displays output, google chrome gives error

alert(JSON.stringify(myArray));
//output  [{name:"two", value:"2"}]