4

我创建了一个数组,如:

myarr: [ 
    { name:'London', population:'7000000' },
    { name:'Munich', population:'1000000' }
]

在某些时候,我需要向数组中添加一些新元素,但首先我需要检查是否已经存在同名的元素。如果是,则必须更新该值。如果否,则必须创建并添加新元素。如果新元素中的值为零并且该元素存在,则必须将其从数组中删除。

4

2 回答 2

4

你可以这样做

function myFunction(myarr, item) {
    var found = false;
    var i = 0;
    while (i < myarr.length) {
        if (myarr[i].name === item.name) {
            // Do the logic (delete or replace)
            found = true;
            break;
        }
        i++;
    }

    // Add the item
    if (!found)
        myarr.push(item);

    return myarr;
}
于 2013-09-04T13:15:35.167 回答
3

这应该可以解决问题http://jsfiddle.net/tcwqV/

var arr = [ 
    { name:'London', population:'7000000' },
    { name:'Munich', population:'1000000' }
]

var addNewElement = function(arr, newElement) {
    var found = false;
    for(var i=0; element=arr[i]; i++) {
        if(element.name == newElement.name) {
            found = true;
            if(newElement.population === 0) {
                arr[i] = false;
            } else {
                arr[i] = newElement;
            }            
        }
    }
    if(found === false) {
        arr.push(newElement);
    }
    // removing elements
    var newArr = [];
    for(var i=0; element=arr[i]; i++) {
        if(element !== false) newArr.push(element);
    }
    return newArr;
}

arr = addNewElement(arr, {name: 'Paris', population: '30000000'});
console.log(arr);
arr = addNewElement(arr, {name: 'Paris', population: '60000000'});
console.log(arr);
arr = addNewElement(arr, {name: 'Paris', population: 0});
console.log(arr);
于 2013-09-04T13:26:47.040 回答