按指定字符数拆分JSON字符串的JavaScript代码报错:索引与长度需指向字符串内有效位置
Fixing "Index and length must refer to a location within the string" Error in String Splitting Function
Let's break down why your code is throwing that error and fix it step by step.
What's Causing the Error?
- Case-sensitive variable mismatches: You're passing
nCharactersandvalueDeinfoto the function, but the function expectsnCharacterandvalueDeInfo(note the capitalization differences). This can lead to incorrect length values or undefined strings being passed in. - Backwards logic for the final chunk: In your loop, you're slicing the string first before updating the
endvalue to the actual string length. If your string isn't a perfect multiple of 4000 characters, this means you're trying to slice beyond the string's bounds (especially if you're using a .NET-based JS environment like JScript.NET, which enforces strict index bounds). - Unnecessary manual tracking of
begin/end: Your current approach to updating these variables is error-prone and easy to mess up. - Array access oversight: Your
valueDeInfois an array containing a single JSON string, but you're treating it like the string itself, which leads to incorrect length calculations.
Corrected Code
Here's a cleaned-up, working version of your function with fixes for all the above issues:
var splitA = []; function separatedFields(totalLength, targetString) { const chunkSize = 4000; const chunks = []; const totalChunks = Math.ceil(totalLength / chunkSize); for (let i = 0; i < totalChunks; i++) { const start = i * chunkSize; // Ensure we never go beyond the actual string length const end = Math.min(start + chunkSize, totalLength); chunks.push(targetString.slice(start, end)); } return chunks; } // Fix variable capitalization and access the actual string inside the array const valueDeInfo = ['{"Status":"OK","RequestID":"e5517d4e-ee43-451a-bbe8-09f9fc714c21","Results":[{"CustomerKey":null,"Name":"Control","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":3,"DefaultValue":"1","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"CategoryID","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":8,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsSendable","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":2,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Name","ObjectID":null,"FieldType":"Text","IsPrimaryKey":true,"MaxLength":50,"Ordinal":0,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsRequired","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":10,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"infoDE3","ObjectID":null,"FieldType":"Text","IsPrimaryKey":false,"MaxLength":4000,"Ordinal":18,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Description","ObjectID":null,"FieldType":"Text","IsPrimaryKey":false,"MaxLength":4000,"Ordinal":6,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"ModifiedDate","ObjectID":null,"FieldType":"Date","IsPrimaryKey":false,"MaxLength":0,"Ordinal":7,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}']; const totalLength = valueDeInfo[0].length; // Get length of the actual JSON string, not the array splitA = separatedFields(totalLength, valueDeInfo[0]); Write("ARRAY FIRST 4000: " + splitA[0]);
Key Improvements
- Variable consistency: Fixed case mismatches so the function receives correct inputs.
- Safe slicing: Uses
Math.min()to guarantee we never slice beyond the string's actual length, eliminating the index out-of-bounds error. - Simplified logic: Calculates chunk start/end positions directly from the loop index, removing the need to manually track
beginandend(which was the source of your final chunk bug). - Array correction: Accesses
valueDeInfo[0]since your original variable is an array containing a single JSON string, not the string itself.
内容的提问来源于stack exchange,提问作者Paullogon
相关产品推荐
相关产品推荐

