JavaScript实现的类字典插入或更新方法实例

<script type="text/javascript"> function insertOrUpdate(array, keyName, keyVal, fieldNames, fieldVals) { var hasExist = false; var len = array.length; for (var i = 0; i < len; i++) { if (array[i][keyName] && array[i][keyName] == keyVal) { // 已存在则直接更新 hasExist = true; for (var j = 0; j < fieldNames.length; j++) { array[i][fieldNames[j]] = fieldVals[j]; } } } if (!hasExist) {// 如果不存在则插入 array[len] = {}; array[len][keyName] = keyVal; for (var k = 0; k < fieldNames.length; k++) { array[len][fieldNames[k]] = fieldVals[k]; } } } var orders = [ { "OrderId" : 1, "OrderAmount" : { "OldValue" : 10, "NewValue" : 20 } }, { "OrderId" : 2, "OrderAmount" : { "OldValue" : 20, "NewValue" : 30 } }]; insertOrUpdate(orders, "OrderId", 1, ["OrderAmount"], [{"OldValue": 145, "NewValue": 1125}]); console.dir(orders); insertOrUpdate(orders, "OrderId", 3, ["OrderAmount"], [{"OldValue": 75, "NewValue": 95}]); console.dir(orders); </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgdgjz.html