用于验证字符串中括号的 JS 函数

2023-11-29

伙计们!我想问你如何创建一个函数来检查字符串中的括号是否正确放置。例如“(a + b).4,2 - )c + 5)”,我必须检查括号。我尝试了一些方法,但似乎不起作用(抱歉,我是 javascript 的新手):

function checkBrackets(str){
	var newOrder = [];
	var bracket1 = "(";
	var bracket2 = ")";
	for(var bracket1 in str){
		
			newOrder.push("1");
	}

	for(bracket2 in str){
		
			newOrder.pop();
	}

	if(newOrder.length == 0){
		console.log("Right!" + newOrder);
	} else{
		console.log("Wrong!" + newOrder);
	}
}

checkBrackets('( ( a + b ) / 5 – d )');

我尝试使用 for-in 循环遍历字符串,每当它遇到“(”时,就会将“1”添加到数组中。当它遇到“)”时,就会从数组中删除一个“1”。最后,如果数组为空,我可以得出结论,括号放置正确,如果不是,则不是。


你可以这样做:

// str is the string to parse
function checkBrackets(str){
    // depth of the parenthesis
    // ex : ( 1 ( 2 ) ( 2 ( 3 ) ) )
    var depth = 0;
    // for each char in the string : 2 cases
    for(var i in str){   
        if(str[i] == '('){
            // if the char is an opening parenthesis then we increase the depth
            depth ++;
        } else if(str[i] == ')') {
            // if the char is an closing parenthesis then we decrease the depth
            depth --;
        }  
        //  if the depth is negative we have a closing parenthesis 
        //  before any matching opening parenthesis
        if (depth < 0) return false;
    }
    // If the depth is not null then a closing parenthesis is missing
    if(depth > 0) return false;
    // OK !
    return true;
}
console.log(checkBrackets('( ( a + b ) / 5 – d )')); // true
console.log(checkBrackets('( ( ) a + b ) / 5 – d )')); // false
console.log(checkBrackets('( ) ) ( ( a + b ) / 5 – d )')); // false
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用于验证字符串中括号的 JS 函数 的相关文章