Home  >  Article  >  Web Front-end  >  How to determine whether a string is all 0 in javascript

How to determine whether a string is all 0 in javascript

青灯夜游
青灯夜游Original
2021-12-08 12:02:573913browse

Method: 1. Use split() to convert the string into a character array, one character corresponds to one array element; 2. Use every() to check whether the elements in the character array are all 0, and if they are all 0 will return true, the syntax is "arr.every(function f(v){return v==0;})".

How to determine whether a string is all 0 in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In JavaScript, if you want to detect whether the characters in a string are all 0, you can use the every() function of the array.

  • Use the split() function to convert the string into a character array. One character corresponds to one array element.

  • Use the every() function to detect whether the character elements in the character array are all 0. If all are 0, "true" will be returned. If one is not 0, "false" will be returned. .

Implementation code:

function f (value) {
        return value == 0;
}
var str="00000";
var arr=str.split('');
if (arr.every(f)) {
    console.log("都为0");
}else{
    console.log("不全为0");
}

How to determine whether a string is all 0 in javascript

function f (value) {
        return value == 0;
}
var str="00100";
var arr=str.split('');
if (arr.every(f)) {
    console.log("都为0");
}else{
    console.log("不全为0");
}

How to determine whether a string is all 0 in javascript

Description:

The every() method is used to determine whether all elements of the array meet the specified conditions.

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to determine whether a string is all 0 in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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