我们可以在 JavaScript 中动态创建数组吗?是的,当然,我们可以。
本文给出了在 JavaScript 中创建动态数组的示例;有必要了解静态数组与动态数组。
目录
4.使用DOM Elements和jQuery在JavaScript 中创建动态数组
1.JavaScript 中的主题与动态目录
通常,我们在创建数组时确定数组的大小或长度;此数组类型是静态或固定数组。另一方面,动态数组意味着在运行时分配内存并填充值。
它们还可以在运行时更新它们的大小,这克服了静态数组的限制。
2.在JavaScript prompt()中创建动态目录
为了创建动态数组,我们可以通过两种方式获取用户的输入,第一种是prompt()
,第二种是<input>
元素。
该prompt()
方法显示一个对话框,提醒用户输入一个值。如果用户单击OK
,则该prompt()
方法返回输入值,否则返回null
。
另一方面,我们也可以使用<input>
标签来获取用户的输入。它是一个 HTML 元素,有多种类型。
我们将使用<input>
. type=text
让我们从使用prompt()
.
JavaScript 代码:
var inputArr = [];
var tempVariable = '';
do {
tempVariable = prompt("Enter a number. Press cancel or leave empty to exit.");
if (tempVariable === "" || tempVariable === null) {
break;
} else {
inputArr.push(tempVariable); // the array will grow dynamically
}
} while (1);
document.write(inputArr);
输出:
在这里,如果输入为空或null
;我们退出代码 inptuArr
否则,使用 方法将Push()输入值插入。
3.在JavaScript中使用<input>标签创建动态数组
在下面的示例代码中,我们使用<input>
元素从用户那里获取输入,并在运行时将其填充到数组中。
HTML 代码:
<html>
<head>
<title>Document</title>
</head>
<body>
<input type="text" id="num" />
<input type="button" id="addBtn"onclick="addValues();" value="Add" />
<br />
<input type="button" id="showBtn" onclick="showValues();" value="Show" />
<div id="container"></div>
</body>
</html>
CSS 代码:
#addBtn{
background-color: lightgreen;
}
#showBtn{
background-color: orange;
}
JavaScript 代码:
var arr = [];
function addValues() {
var input = document.getElementById('num');
if(input.value == "" || input.value == "null")
alert("The element can't be empty or null");
else
arr.push(input.value);
input.value = '';
}
function showValues() {
var html = '';
for (var i=0; i<arr.length; i++) {
html += '<div>' + arr[i] + '</div>';
}
var container = document.getElementById('container');
container.innerHTML = html;
}
输出:
在这里,我们检查用户按下Add
按钮时的输入值。如果它是空null
的 或 ,我们会提醒用户并再次输入。
该Show
按钮显示数组的所有元素。
4.使用DOM Elements和jQuery在JavaScript 中创建动态数组
使用 DOM 元素创建和填充动态数组。让我们使用 jQuery 来了解我们如何做到这一点。
HTML 代码:
<html>
<head>
<title>Document</title>
</head>
<body>
<ul id="filelisting">
<li><a href="path/to/file1.docx">File Title1</a></li>
<li><a href="path/to/file.docx">File Title2</a></li>
<li><a href="path/to/file3.docx">File Title3</a></li>
</ul>
</body>
</html>
JavaScript 代码:
var fileList = [];
$('ul#filelisting li a').each(function(){
fileList.push({
File_Title: $(this).text(),
File_Path:$(this).attr("href")
});
});
console.log("The content of the array is given below:");
console.log(fileList);
输出:
"The content of the array is given below:"
[{
File_Path: "path/to/file1.docx",
File_Title: "File Title1"
}, {
File_Path: "path/to/file.docx",
File_Title: "File Title2"
}, {
File_Path: "path/to/file3.docx",
File_Title: "File Title3"
}]
本文含有隐藏内容,请 开通VIP 后查看