Jan*_*nis 1 arrays indexing jquery
我有以下代码,需要检查一个值是否作为数组键存在.
我似乎无法生成index密钥,即使它确实存在,任何帮助都会很棒.
码:
var run = { // store the actions to trigger
block : function() {
console.log('Blocking…');
},
warning : function() {
console.log('Warning…');
}
};
console.log( $.inArray( 'warning' , run ) );
Run Code Online (Sandbox Code Playgroud)
据我所看到的,warning内部存在run{}和应该返回index的1.
为什么上面没有找到(index返回为-1).
谢谢阅读.
run不是一个数组(它只是一个普通的对象)所以它没有索引.即使block之前warning,对象也是无序的,所以你不能说run索引为1.
要检查对象是否具有特定键,只需检查:
if ('warning' in run) {...}
Run Code Online (Sandbox Code Playgroud)
要么:
if (run.warning) {...}
Run Code Online (Sandbox Code Playgroud)