本文實例講述了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程序設計有所幫助。