In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about what the top ten JavaScript mistakes are and how to avoid them. Many people may not know much about them. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something from this article.
To give back to our developer community, we looked at a database of thousands of projects and found the top 10 errors in JavaScript. I will show you the causes of them and how to prevent them from happening. If you avoid these "traps", it will make you a better developer.
Because data is king, we collect, analyze and rank the top 10 JavaScript errors. Rollbar collects all the errors for each project and summarizes how many times each project has occurred, which is achieved by grouping errors according to their fingerprints.
We focus on the mistakes that are most likely to affect you and your users. To this end, we rank errors according to the number of projects that have encountered errors in different companies.
Here are the top ten JavaScript errors:
Each error is shortened in order to make it easier to read, so let's take a closer look at each problem to determine what caused these problems and how to avoid them.
1. Uncaught TypeError: Cannot read property
If you are a JavaScript developer, you may have seen this error. This happens in Chrome when you read properties or call methods on undefined objects. You can easily test in the Chrome developer console.
There are many reasons for this, but the common reason is that the state is not initialized properly when rendering UI components. Let's look at an example of how this happens in real-world applications. We will choose React, but the same principle of incorrect initialization applies to Angular,Vue or any other framework.
Class Quiz extends Component {componentWillMount () {axios.get ('/ thedata') .then (res = > {this.setState ({items: res.data});} render () {return ({this.state.items.map (item = > {item.name})});}}
Here are two important things to be aware of:
The state of the component, such as this.state, starts with the undefined state.
When you get data asynchronously, whether the data is obtained in the constructor componentWillMount or componentDidMount, the component will render at least once before the data is loaded. When Quiz renders for the first time, this.state.items is undefined. This in turn means that ItemList will get an undefined items, and you will get an error in the console-- an error of "UncaughtTypeError: Cannot read property 'map' of undefined".
This is easy to solve, and the easiest way is to initialize the state with reasonable default values in the constructor.
Class Quiz extends Component {/ / added this: constructor (props) {super (props); this.state = {items: [] / default};} componentWillMount () {axios.get ('/ thedata') .then (res = > {this.setState ({items: res.data});}) } render () {return ({this.state.items.map (item = > {item.name}));}}
The actual code in your application may be different, but I hope I have given you enough clues to fix or avoid this problem in your application. If not, please read on, as I will introduce more examples of related errors below.
2. TypeError: 'undefined' is not an object (evaluating
This is an error that occurs when reading properties in Safari or calling methods on undefined objects, which you can easily test in the Safari developer console. This is basically the same as the above error for Chrome, but Safari uses a different error message.
3.TypeError: null is not an object (evaluating
This is an error that occurs when reading properties in Safari or calling methods on null objects, which you can easily test in the Safari developer console.
Interestingly, in JavaScript, null and undefined are different, which is why we see two different error messages. Undefined is usually an unassigned variable, while null indicates that the value is blank. To verify that they are equal, try using the strict equality operator.
One way this error can occur in a real example is to try to use the DOM element in the JavaScript before loading the element, because DOM API returns null for a blank object reference.
Any JS code that executes and processes the DOM element should be executed after the DOM element is created. The JS code is interpreted from top to bottom in HTML format, so if there is a tag before the DOM element, the JS code inside the script tag will be executed when the browser parses the HTML page. This error occurs if the DOM element has not been created before the script is loaded.
In this example, we can solve this problem by adding an event listener, which will notify us when the page is ready. Once the addEventListener,init () method is triggered, the DOM element can be used.
Function init () {var myButton = document.getElementById ("myButton"); var myTextfield = document.getElementById ("myTextfield"); myButton.onclick = function () {var userName = myTextfield.value;}} document.addEventListener ('readystatechange', function () {if (document.readyState = "complete") {init ();}})
4. (unknown): Script error
A script error occurs when an uncaught JavaScript error violates the cross-source policy and crosses domain boundaries. For example, if you host your JavaScript code on CDN, any uncaught errors (errors bubbling into the _ window.onerror handler rather than those caught in try-catch) will be reported as "Script error" rather than containing useful information. This is a browser security measure designed to prevent data from being transferred across domains, otherwise the domain will not be able to communicate.
To get a real error message.
Send Access-Control-Allow-Origin header
Setting the Access-Control-Allow-Origin header to * means that resources can be accessed correctly from any domain. However, dealing with multiple domains is complex, and if using CDN may cause caching problems, it may not be worth the effort.
Here are some examples of how to set this header in various environments:
Apache
In the folder where the JavaScript file will be provided, create an .htaccess file with the following:
Header add Access-Control-Allow-Origin "*"
Nginx
Add the add_header directive to the location block that provides the JavaScript file:
Location ~ ^ / assets/ {add_header Access-Control-Allow-Origin *;}
HAProxy
Add the following to the asset backend that provides the JavaScript file:
Rspadd Access-Control-Allow-Origin:\ *
Set crossorigin = "anonymous" on the script tag
In your HTML source code, set crossorigin= "anonymous" on the script tag for each script for which you set the Access-Control-Allow-Origin header. Before adding the crossorigin attribute to the script tag, make sure that you have verified that the header has been sent for the script file. In Firefox, if the crossorigin attribute exists but there is no Access-Control-Allow-Origin header, the script will not be executed.
5. TypeError: Object doesn't support property
This is an error that occurs in IE, and you can test it in the IE developer console when you call the method of undefined.
This is equivalent to the error "TypeError: 'undefined' is not a function" in Chrome. Yes, different browsers may have different error messages for the same logic error.
This is a common problem with IE in Web applications that use JavaScript namespaces, in which case 99.9% of the problem is that IE cannot bind methods in the current namespace to the this keyword.
For example, if your JS namespace Rollbar uses the isAwesome method. In general, if you are in the Rollbar namespace, you can call the isAwesome method using the following syntax:
This.isAwesome ()
IE, on the other hand, does not. Therefore, when using JS namespaces, the safest way is to prefix them with the actual namespace.
Rollbar.isAwesome ()
6. TypeError: 'undefined' is not a function
This is the error that occurs in Chrome when you call the function of undefined. You can test this in the Chrome developer console and the Mozilla Firefox developer console.
As the coding techniques and design patterns of JavaScript become more complex over the years, the scope of self-reference in callbacks and closures increases accordingly, which is a fairly common source of confusion of one kind or another.
Consider the following sample code snippet:
Function clearBoard () {alert ("Cleared");} document.addEventListener ("click", function () {this.clearBoard (); / / what is this "this"? });
If you execute the above code, and then click the page, it will result in the following error "Uncaught TypeError:this.clearBoard not a function". The reason is that the anonymous function being executed is in the context of the document, while clearBoard is defined in window.
The traditional solution compatible with older browsers is to simply save a reference to it in a variable, and then the closure can inherit that variable. For example:
Var self = this; document.addEventListener ("click", function () {self.clearBoard ();})
In addition, in newer browsers, you can use the bind () method to pass the correct reference:
Document.addEventListener ("click", this.clearBoard.bind (this))
7. Uncaught RangeError: Maximum call stack
This is an error that occurs in Chrome browsers in several cases, one of which is to call non-terminating recursive functions. You can test this in the Chrome developer console.
This can also happen if you pass a value to a function that is out of range. The input values of many functions accept only a specific range of digits, for example, Number.toExponential (digits) and Number.toFixed (digits) accept numbers between 0 and 20, while Number.toFixed (digits) accepts numbers between 1 and 21.
Var a = new Array (4294967295); / / OK var b = new Array (- 1); / / range error var num = 2.555555; [xss_clean] ln (num.toExponential (4)); / / OK [xss_clean] ln (num.toExponential (- 2)); / / range error! Num = 2.9999; [xss_clean] ln (num.toFixed (2)); / / OK [xss_clean] ln (num.toFixed (25)); / / range error! Num = 2.3456; [xss_clean] ln (num.toPrecision (1)); / / OK [xss_clean] ln (num.toPrecision (22)); / / range error!
8. TypeError: Cannot read property 'length'
This is an error in the Chrome browser because you can test it in the Chrome developer console by reading the length property of the undefined variable.
Normally, you can find the defined length on the array, but you may encounter this error if the array is not initialized or the variable name is hidden in another context. Let's learn about this error through the following example.
Var testArray= ["Test"]; function testFunction (testArray) {for (var I = 0; I < testArray.length; iArray +) {console.log (testArray [I]);} testFunction ()
This means that even if you have a variable named testArray, parameters with the same name within the function will still be treated as local parameters.
You can solve the problem in two ways:
Delete parameters in function declaration statements (it turns out that you want to access variables declared outside the function, so you don't need to use arguments for the function)
Var testArray = ["Test"]; / * precondition: define testArray * / function testFunction (/ * No params * /) {for (var I = 0; I < testArray.length; iArray +) {console.log (testArray [I]);}} testFunction () outside the function.
Call the function and pass it the array we declared.
Var testArray = ["Test"]; function testFunction (testArray) {for (var I = 0; I < testArray.length; iArray +) {console.log (testArray [I]);} testFunction (testArray)
9. Uncaught TypeError: Cannot set property
When we try to access an undefined variable, it always returns undefined, and we cannot get or set any undefined properties. In this case, the application will throw a "Uncaught TypeError:Cannot set property".
For example, in a Chrome browser:
If the test object does not exist, the error throws "Uncaught TypeError:Cannot set property".
10. ReferenceError: event is not defined
This error is raised when you try to access undefined or variables that are out of the current range. You can test it very easily in a Chrome browser.
If you receive this error when using the event handling system, make sure you use the incoming event object as a parameter. Older browsers such as IE provide global variable events, while Chrome automatically appends event variables to handlers. Firefox does not add it automatically. Libraries such as jQuery try to regulate this behavior, however, it is best to use the method passed to the event handler function.
Document.addEventListener ("mousemove", function (event) {console.log (event);})
Summary
It turns out that many of them are null or undefined errors. If you use strict compiler options, static type checking systems like Typescript can help you avoid using them. It can warn you if a type is expected but has not been defined.
After reading the above, do you have any further understanding of the top 10 JavaScript errors and how to avoid them? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.