本文實例講述了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>
希望本文所述對大家的javascript程式設計有所幫助。