我需要检查我从 PHP 获得的数字数组中是否存在一个数字,如果是,则渲染来自 iosocket 的数据。但由于某种原因,此代码不起作用。数组返回 20, 25,要检查的数字是 20 f.example
<script>
var negozi_seguiti = <?php echo json_encode($negozi_seguiti); ?>;
var post = io('http://1clickfashion.com:3002');
post.on("test-channel:App\Events\Post", function(message){
// increase the power everytime we load test route
alert(negozi_seguiti);
if (jQuery.inArray(negozi_seguiti, message.data.negozio) == -1) {
$('#timeline').addClass("timeline");
$('#timeline').prepend(message.data.timeline);
$('#rocket').hide();
}
});
</script>
我错了什么?
你误用了inArray
,你颠倒了参数,像这样用:
var arr = [20, 21];
console.log($.inArray(20, arr))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
我还建议您使用 indexOf
它的工作方式相同,但直接在数组上调用,从而降低犯此类错误的风险:
var arr = [20, 21];
console.log(arr.indexOf(20));
它让你的代码更清晰,你摆脱了jQuery,最后它更快。
如果你在数组negozi_seguiti
变量中获得正确的值,那么你需要像波纹管一样更改$.inArray('search_value', 'yourarray')
。
var negozi_seguiti = <?php echo json_encode($negozi_seguiti); ?>;
var post = io('http://1clickfashion.com:3002');
post.on("test-channel:App\Events\Post", function(message) {
// increase the power everytime we load test route
alert(negozi_seguiti);
if (jQuery.inArray(message.data.negozio, negozi_seguiti) == -1) {
$('#timeline').addClass("timeline");
$('#timeline').prepend(message.data.timeline);
$('#rocket').hide();
}
});