Javascript loop an array to find numbers divisible by 3

前端 未结 8 1144
清歌不尽
清歌不尽 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:20

    You can use Array#filter for this task.

    filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value or a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

    function loveTheThrees(array) {
        return array.filter(function (a) {
            return !(a % 3);
        });
    }
    document.write('
    ' + JSON.stringify(loveTheThrees([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 0, 4) + '
    ');

提交回复
热议问题