JavaScript/jQuery 创建包括两个数字之间的整数数组
有多种方法可以在JavaScript/jQuery中创建一个包含两个数字之间的所有整数的数组,以下是一些常见的方法:
- 使用循环
- 使用Array.from()方法
- 使用jQuery
方法1:使用循环
for循环或while循环遍历两个给定数字之间的所有整数,并将它们推入一个数组中。
语法:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
示例: 在这个例子中,我们将会看到使用 for循环和push()函数 。
Javascript
function createArray(start, end) {
let result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
}
let result = createArray(1, 5);
// Output: [1, 2, 3, 4, 5]
console.log(result);
输出
[ 1, 2, 3, 4, 5 ]
方法2:使用 Array.from() 方法
使用 Array.from()方法 创建一个包含两个数字之间的所有整数的数组,包括这两个数字。
语法:
function createArray(start, end) {
return Array.from({length: end - start + 1},
(_, index) => start + index);
}
Example: 在这个例子中,我们将看到使用 Array.from()方法。
Javascript
function createArray(start, end) {
return Array.from({ length: end - start + 1 },
(_, index) => start + index);
}
let result = createArray(1, 5);
// Output: [1, 2, 3, 4, 5]
console.log(result);
输出结果
[ 1, 2, 3, 4, 5 ]
方法3: 使用jQuery的循环方法
该程序首先通过定义数字范围的起始和结束位置,并将其分别设置为start和end。在这种情况下,它们分别设置为3和9。通过使用map,我们遍历数字并获取其值。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<script src=
"http://code.jquery.com/jquery-3.1.0.min.js"
integrity=
"sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="
crossorigin="anonymous">
</script>
</head>
<body>
<script>
// Start and end
let start = 3;
let end = 9;
// Create an array of all integers
// between start and end using jQuery
let range =
$.map(new Array(end - start + 1),
function (val, index) {
return index + start;
});
document.write("[" + range.join(", ") + "]");
</script>
</body>
</html>
输出: