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

Sha*_*haf 2 javascript arrays expression numbers brackets

伙计们!我想问你一个函数如何检查字符串中的括号是否正确放置。例如“((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 )');
Run Code Online (Sandbox Code Playgroud)

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

nob*_*be4 5

您可以这样操作:

// 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
Run Code Online (Sandbox Code Playgroud)