带有JSON字符串化对象的javascript索引
我试图找出是否存在这样的字符串:带有JSON字符串化对象的javascript索引,javascript,jquery,Javascript,Jquery,我试图找出是否存在这样的字符串: var test1 = '{"packageId":"1","machineId":"1","operationType":"Download"},{"packageId":"2","machineId":"2","operationType":"Download"}'; alert("found: " + test1.indexOf('{"packageId":"1","machineId":"1","operationType":"Download"}',
var test1 = '{"packageId":"1","machineId":"1","operationType":"Download"},{"packageId":"2","machineId":"2","operationType":"Download"}';
alert("found: " + test1.indexOf('{"packageId":"1","machineId":"1","operationType":"Download"}', 0));
但是,结果始终为0
有什么用?以防万一这不是个玩笑
String.prototype.indexOf
返回目标字符串中匹配字符串的出现时间,因为您只需查找该行的第一次出现时间,它正确地返回零
如果修改搜索字符串(例如,使用一些随机字母),您将得到-1
,因为找不到它
有一种做法是使用二进制not运算符,将.indexOf()
的结果转化为布尔表达式。这看起来像
var res = test1.indexOf('{"packageId":"1","machineId":"1","operationType":"Download"}');
if( ~res ) {
// we have a match
} else {
// no match at all
}
if( !!~res ) { }
not运算符将对字节中的每一位求反,也就是用于确定值是正值还是负值的额外位。因此,由于在ECMAscript中只有很少的值被计算为falsy值,因此负值将被计算为true
要真正得到一个布尔结果,它看起来像
var res = test1.indexOf('{"packageId":"1","machineId":"1","operationType":"Download"}');
if( ~res ) {
// we have a match
} else {
// no match at all
}
if( !!~res ) { }
在这种情况下,这也是不必要的
使用.indexOf()
(数组也是如此)获得“正确”结果的更常用做法是检查结果是否大于-1
if( res > -1 ) { }
ya它的正确索引xOf将返回您提到的字符串的起始索引,即y,它给出0。如果字符串不存在,则返回-1 一些示例 var sample=“欢迎使用javascript” 匹配:
if(sample.indexOf("welcome",0)>-1)
alert("match");
else
alert("Not match")l
0是您正在搜索的文本的索引(位置)。因此,如何查找字符串/或字符串的一部分是否存在?