JavaScript 循环推送到新数组

JavaScript loop push to new array

我正在尝试将所有可被 3 整除的数字放入一个新数组 "threes",但遇到了为什么此代码不起作用的问题。

var numbers = function () {
  var threes =[]
  for (i = 0; i < numbers.length; i++) {
    if (iLoveThree[i] % 3 === 0){
      threes.push(numbers[i])
    }
  }
  return threes
}

我认为只对数字使用过滤器会更简单

var threes = numbers.filter(function(number) {
  return number % 3 === 0;
});

我已经解决了你的问题,创建一个新的 html 文件并输入:

<!doctype html>
<HTML>

    <BODY>
        <SCRIPT>
            (function(){
                var numbers = function (iLoveThree) {
                    var threes =[];
                    for (i = 0; i < iLoveThree.length; i++) {
                        if (iLoveThree[i] % 3 === 0){
                            threes.push(iLoveThree[i]);
                        }
                      }
                    return threes;
                }
                alert(numbers([1, 2, 3, 4, 5, 6]));
            })();
        </SCRIPT>
    </BODY>
</HTML>

希望对您有所帮助:)
解释:
- 你需要包含函数参数,这个参数将在函数内部访问(参数名为iLoveThree)
- 您使用的是 numbers 变量,但之前未声明此变量,我通过将 numbers 更改为 iLoveThree
来解决此问题 - 你错过了几个; (分号),很简单但是会给你带来很多麻烦

PS : 感谢RobG提醒我给出解释。

你的例子有几个问题:

  • 您已将函数命名为 "numbers",但随后还在函数
  • 中引用了一个名为 "numbers" 的不存在的数组
  • iLoveThree 被引用为一个数组,但从未被声明

根据应用程序的需要,您可能需要获取最小值和最大值之间的所有可被三整除的数字,或者您可能需要从预定义的数字中提取可被三整除的数字大批。我在下面的代码中包含了这两种情况的示例:

var isDivisibleByThree = function(num){
  return i % 3 === 0;
}

var getThrees = function (min, max) {
  // given a numeric min and max value,
  // return all numbers from a minimum to a maximum value that are divisible by three
  var threes =[];
  for (i = min; i <= max; i++) {
    if (isDivisibleByThree(i)){
      threes.push(i);
    }
  }
  return threes;
}

var getThreesFromArray = function(numbers){
  // given an array of numbers, 
  // return a subset of that array including  only numbers divisible by 3
  var threes = [];
  for (i = 0; i < numbers.length; i++) {
    if (isDivisibleByThree(numbers[i])){
      threes.push(i);
    }
  }
  return threes;
                 
}
var fromZeroTo50 = getThrees(0, 50);
var fromArray = getThreesFromArray([5, 0, 6, 17, 12, 4, 18]);

// Grab example values and display them in the HTML for demonstration purposes
document.getElementById("fromZeroTo50").innerHTML = fromZeroTo50.join(",");
document.getElementById("fromArray").innerHTML = fromArray.join(",");
<h2>Get all threes from 0 to 50: </h2>
<div id="fromZeroTo50"></div>

<h2>Get threes from a pre-defined array: </h2>
<div id="fromArray"></div>