Home > Web Front-end > JS Tutorial > A brief discussion on variable initialization in js_javascript skills

A brief discussion on variable initialization in js_javascript skills

WBOY
Release: 2016-05-16 16:16:13
Original
1242 people have browsed it

I wrote a function in js that removes leading and trailing spaces and specific characters. The code is as follows:

Copy code The code is as follows:

function trim(str, charlist) {
Return str.replace(new RegExp('^[\s' charlist '] |[\s' charlist '] $', 'g'), '');
}

The code looks fine and runs without errors.

Until today, when I searched for "note3" in the search bar, I found that the search content in the address bar changed to "ote3", while other letters or numbers starting with it are normal. What to search for, address That's what's in the column.

After debugging the code, change the code to:

Copy code The code is as follows:

function trim(str, charlist) {
var charlist = charlist || "";
Return str.replace(new RegExp('^[\s' charlist '] |[\s' charlist '] $', 'g'), '');
}

Added initialization of charlist in the function. When searching for "note3", the result is correct.

Although js is a weakly typed language, using variables does not require initialization. When running, the code will automatically convert and assign values. However, doing so will cause some unexpected problems, so it is very necessary to initialize all variables used.

That’s it for today, I hope you guys like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template