Javascript - Get position of the element of the array

前端 未结 5 1434
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 20:36

For instance, a variable named arrayElements of array type contains [1,2,3,4].

How do i get the position of which that has the value \"3\" in the array variable besi

5条回答
  •  情歌与酒
    2020-12-13 20:57

    As was already pointed out by some answers, arrays in newer browsers have methods like indexOf map and forEach that are very convenient for avoiding writing lots of for-loops.

    If you need to support old environments without these functions I would strongly recommend using a library (or writing one of your own) to implement those very common array operations (kind of how soc suggested).

    var arrayfn = (function(){
        var M = {};
    
        M.indexOf = function(array, item){ ... };
    
        M.contains = function(array, item){ return M.indefOf(array, item) !== -1; };
    
        M.map = function(array, callback){ ... };
    }());
    
    arrayfn.contains([1,2,3], 2);
    

    Most popular JS frameworks should already have most of these builtin anyway. Out of the top of my head I remember Dojo, jQuery and Underscore have some of these functions, for example.

提交回复
热议问题