jquery - 查找数组中的值 .inArray()

标签 jquery arrays

我正在使用 .inArray() 检查数组中是否有“0”值,然后返回 false; 或在存在零时中断该函数。

这是我当前使用的代码:

$(document).ready(function() {

    $('#calc').click(function(e) {

        var drop = $(".drop"),
            c = [],
            g = [];

        //Push values into an array.
        drop.each(function() {
            var $t = $(this),
                cals = $t.val(),
                option = $(':selected', this),
                gly = parseFloat(option.attr('rel'));
            g.push(gly * 2);
            c.push(cals * 2);
        });

        var inthere = jQuery.inArray('0', c) > -1;

        //don't calculate if array is empty
        if (c.length === 0) {
            return false;
        }
        //don't calculate with a '0' value in array
        if (inthere == true) {
            return false;
        }

        //shouldn't display if you haven't added a dropdown OR if the dropdown stayed on the "Default" option
        alert('Passed');
    });

    $('#add').click(function() {
        $('#contain').append('<select class="drop"><option value="" rel="" data-default="true">Default</option><option value="1" rel="2">Option 1</option><option value="3" rel="4">Option 2</option></select>');
    });

});​

当用户将 option 保留为“Default”选项时,传递给 c 的值应为 0。出于某种原因,代码将通过,除非我尚未添加到下拉列表中...

如果 c 数组中有“0”,如何阻止代码继续执行???

这是fiddle

最佳答案

该数组没有与 '0' 匹配的字符串,但有与 0 匹配的数字。

http://jsfiddle.net/DUs8e/1/

var inthere = jQuery.inArray(0, c) > -1;

关于jquery - 查找数组中的值 .inArray(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12803445/

相关文章:

jquery 根据下拉列表中选定的值显示隐藏字段

jquery - 根据选择选项值显示/隐藏复选框

javascript - 如何使用 JS 创建响应式下拉菜单?

ruby-on-rails - rails从哈希数组中选择最大值

arrays - 为什么数组是不变的,而列表是协变的?

python - 使用索引迭代两个 2D numpy 数组

javascript - 如何在 Javascript/jQuery 中的 DIV 中实现无限/无限滚动

JavaScript/jQuery 间隔在 Internet Explorer 中执行两次

c 字符串在超出边界时仍然有效?

c++ - 将 char 数组传递给函数