我试图将所有可被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
}
答案 0 :(得分:2)
我已修复您的问题,创建一个新的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)
- 您使用的是数字变量,但此变量之前尚未声明,我通过将数字更改为iLoveThree来修复此问题
- 你错过了几个; (分号),它很简单但会给你带来很多麻烦
PS:感谢RobG提醒我提供解释。
答案 1 :(得分:1)
我认为在数字上使用过滤器会更简单
var threes = numbers.filter(function(number) {
return number % 3 === 0;
});
答案 2 :(得分:1)
您的示例存在一些问题:
根据您的应用程序的需要,您可能需要将所有可被3整除的数字放在最小值和最小值之间。最大值,或者您可能需要从预定义的数组中提取可分割的三个数字。我在下面的代码中包含了这两种方案的示例:
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>