JavaScript [errors that are easy to ignore]: When a line break occurs, the line feed is lost, and the javascript line feed is resumed.
1. Introduction
In JavaScript, when defining a large string, especially when there is a line break, to look neat and easy to read, the following line breaks are generally used:
var script = "var chart = anychart.pieChart([\ ['Chocolate paste', 5],\ ['White honey', 2],\ ['Strawberry jam', 2],\ ['Сondensed milk', 1]\ ]);\//chart.bounds(0, 0, 100%,100%);\var stage = anychart.graphics.create('container', 600, 400);\ stage.container('container');\ chart.container(stage).draw();\ ";
2. Problems
If we execute this Code directly, we will find that the results are very different from the original expectation. Why?
3. Problem Analysis
Because, as a script, when using a line break, it only ensures the continuity and combination of the string (indicating a complete string at this time), but does not include the line break in the string. That is to say, in the above Code, the script string will not contain line breaks. This is a very serious problem. If the string is a script code and contains a line annotator ("//"), it will change the original logic, the code after the line annotator will be commented out and will not be executed.
For example, in the following example, the script code is encoded and then sent to the background for execution (for example, in Node. js). For demonstration convenience, the code is simply decoded:
<textarea id="textarea1" rows="15" cols="53"></textarea><script lang="javascript">var script = "var chart = anychart.pieChart([\ ['Chocolate paste', 5],\ ['White honey', 2],\ ['Strawberry jam', 2],\ ['Сondensed milk', 1]\ ]);\//chart.bounds(0, 0, 100%,100%);\var stage = anychart.graphics.create('container', 600, 400);\ stage.container('container');\ chart.container(stage).draw();\ "; var script_out = encodeURIComponent( script); var textarea1 = document.getElementById('textarea1'); textarea1.value = decodeURIComponent(script_out);</script>
Running result
We can see that the linefeed in the string script is lost, and the code is in disorder, especially
//chart.bounds(0, 0, 100%,100%);
This line is integrated with the subsequent lines. If you execute this code, the subsequent code will not be executed.
4. Solution
Add the line break \ n after the Code with line comments to avoid comments from the code that follows, or use the range annotator (/**/) to annotate the code.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.