数组列表项搜索

时间:2014-12-03 17:12:26

标签: javascript jquery html arrays

有没有办法做到这一点:

var numbers = [156,845,34,849,5,48,54,8,879];

然后检查数组以查看是否有任何小于10的值并输出每个小于10的项的索引值的条件?

所以上面会输出4& 7

感谢你们每个人现在都在工作

5 个答案:

答案 0 :(得分:1)

var numbers = [156,845,34,849,5,48,54,8,879];

var indexes=[];

numbers.map(function(num,index){ 
    if(num < 10) indexes.push(index);
})
console.log(indexes)

答案 1 :(得分:1)

你能不写一个函数来做这个吗?

function membersLessThan(array, value)
{
    var indices = [];

    for(var i=0; i < array.length; i++)
    {
        if(array[i] < value) indices.push(i);
    }

    return indices;
}

编辑:用法示例:

var numbers = [156,845,34,849,5,48,54,8,879];

// contains 4 and 7
var lessthanten = membersLessThan(numbers, 10);

答案 2 :(得分:1)

results = [];
for(key in numbers) {
    if (numbers[key] < 10) results.push(key);
}
console.log(results);

答案 3 :(得分:1)

此代码似乎有效:

var numbers = [156, 845, 34, 849, 5, 48, 54, 8, 879];

for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] < 10) {
        console.log(numbers.indexOf(numbers[i]));
    }
}

Fiddle

答案 4 :(得分:1)

可以使用.each()。例:

&#13;
&#13;
    var numbers = [156,845,34,849,5,48,54,8,879];
    var ind_arr = [];
    $.each(numbers, function(ind, val){
        if(val < 10){
            ind_arr.push(ind);
        }
    });
    alert(ind_arr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
&#13;
&#13;
&#13;