Javascript loop an array to find numbers divisible by 3

前端 未结 8 1158
清歌不尽
清歌不尽 2021-01-25 05:41

I am needing to find the correct way to have javascript loop through an array, find all numbers that are divisible by 3, and push those numbers into a new array.

Here is

8条回答
  •  花落未央
    2021-01-25 06:31

    Using Filter like suggested by Nina is defiantly the better way to do this. However Im assuming you are a beginner and may not understand callbacks yet, In this case this function will work:

    function loveTheThrees(collection){
            var newArray = []
            for (var i =0; i< collection.length;i++){
                if (myArray[i] % 3 === 0){
                    newArray.push(collection[i])
                }
            }
            return newArray;
        }
    

提交回复
热议问题