Home >Web Front-end >JS Tutorial >js determines whether an array contains a string variable
I encountered a phenomenon recently. Among the data returned by the background, some of the arrays have variable values, and some do not. Below, the editor will share with you an example of using js to determine whether an array contains a string variable. It has a good reference value and I hope it will be helpful to everyone.
For example, the example returned by the background is as follows:
var arr=[ { "status":"success", "activerUserData": [ {"activeUser":"张珊","activeUserMobile":"15542175311","countNum":113,"optionTime":1511341097555}, {"activeUserMobile":"15545932121","countNum":62,"optionTime":1511340911802} ] } ]
Obviously the second piece of data lacks the activeUser variable value , then there will be a problem when rendering data.
The next step is to determine whether the variable is in the array
The indexOf method is used (when there are multiple identical variables in the array Not easy to use)
For example:
var arr = [1,2,3]; console.log(arr.indexOf(1)); // 返回0 console.log(arr.indexOf(5)); // 返回-1
It’s very simple. Just judge whether indexOf() is 0 or -1 in the for loop, and then make the corresponding Just deal with it.
Related recommendations:
How to use JS to determine the current domain name and jump to the specified page
How to use JS to determine whether it is an array
Use js to determine whether an array contains an element (similar to in_array() in php)
The above is the detailed content of js determines whether an array contains a string variable. For more information, please follow other related articles on the PHP Chinese website!