如何使用json表单删除javascript数组中的项
我有这个json结构,我把它做成了一个数组。我试图删除该条目,但此代码在我身上失败:如何使用json表单删除javascript数组中的项,javascript,Javascript,我有这个json结构,我把它做成了一个数组。我试图删除该条目,但此代码在我身上失败: 您可以使用属性筛选器来匹配历史记录列表中的项目。下面是这样做的快速代码示例,我对您的历史记录列表做了一些修改 在FF中的快速测试表明它是有效的 var historyList = []; // assuming this already has the array filled function addToHistory(name, notes) { var newHistory = {
您可以使用属性筛选器来匹配历史记录列表中的项目。下面是这样做的快速代码示例,我对您的历史记录列表做了一些修改 在FF中的快速测试表明它是有效的
var historyList = []; // assuming this already has the array filled
function addToHistory(name, notes) {
var newHistory = {
ID: new Date().getTime(),
Name: name,
DoseDate: "Somedate",
ResultDate: "SomeResultDate",
Notes: notes,
toString: function() {return this.Name;}
};
historyList.push(newHistory);
};
var Util = {};
/**
* Gets the index if first matching item in an array, whose
* property (specified by name) has the value specified by "value"
* @return index of first matching item or false otherwise
*/
Util.arrayIndexOf = function(arr, filter) {
for(var i = 0, len = arr.length; i < len; i++) {
if(filter(arr[i])) {
return i;
}
}
return -1;
};
/**
* Matches if the property specified by pName in the given item,
* has a value specified by pValue
* @return true if there is a match, false otherwise
*/
var propertyMatchFilter = function(pName, pValue) {
return function(item) {
if(item[pName] === pValue) {
return true;
}
return false;
}
}
/**
* Remove from history any item whose property pName has a value
* pValue
*/
var removeHistory = function(pName, pValue) {
var nameFilter = propertyMatchFilter(pName, pValue);
var idx = Util.arrayIndexOf(historyList, nameFilter);
if(idx != -1) {
historyList.splice(idx, 1);
}
};
// ---------------------- Tests -----------------------------------
addToHistory("history1", "Note of history1");
addToHistory("history2", "Note of history2");
addToHistory("history3", "Note of history3");
addToHistory("history4", "Note of history4");
alert(historyList); // history1,history2,history3,history4
removeHistory("Name", "history1");
alert(historyList); // history2,history3,history4
removeHistory("Notes", "Note of history3");
alert(historyList); // history2,history4
var historyList=[];//假设已经填充了数组
函数addToHistory(名称、注释){
var newHistory={
ID:new Date().getTime(),
姓名:姓名,,
多塞达特:“某日”,
结果日期:“SomeResultDate”,
注:注:,
toString:function(){返回this.Name;}
};
historyList.push(新历史);
};
var Util={};
/**
*获取数组中第一个匹配项的索引
*属性(由名称指定)具有由“值”指定的值
*@返回第一个匹配项的索引,否则为false
*/
Util.arrayIndexOf=函数(arr,过滤器){
对于(变量i=0,len=arr.length;i
整个数组.prototype.remove
函数可以内联如下:
function removeEntry(value) {
historyList = $.grep(historyList, function(item) {
return (item.ID !== value);
});
}
当然,您可以创建一个函数来包装$.grep
或谓词。(如果您这样做,您可能不想修改Array.prototype
;更喜欢修改historyList
本身(使用Array.prototype.splice
)或在别处创建(可能是静态的)函数。)
此外,据我所知,这个问题与您在问题中提到的SO问题无关。注意:您使用的是对象文字,而不是JSON。JSON则有所不同。见:
function removeEntry(value) {
historyList = $.grep(historyList, function(item) {
return (item.ID !== value);
});
}