Javascript - Get position of the element of the array

前端 未结 5 1435
佛祖请我去吃肉
佛祖请我去吃肉 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:50

    Or simple use a for loop:

    function getPosition(elementToFind, arrayElements) {
        var i;
        for (i = 0; i < arrayElements.length; i += 1) {
            if (arrayElements[i] === elementToFind) {
                return i;
            }
        }
        return null; //not found
    }
    
    getPosition(3, [1, 2, 3, 4]);
    

提交回复
热议问题