数组通常被描述为“像列表一样的对象”; 简单来说,数组是一个包含了多个值的对象。数组对象可以存储在变量中,并且能用和其他任何类型的值完全相同的方式处理,区别在于我们可以单独访问列表中的每个值,并使用列表执行一些有用和高效的操作,如循环 - 它对数组中的每个元素都执行相同的操作。也许我们有一系列产品和价格存储在一个数组中,我们想循环遍历所有这些产品,并将它们打印在发票上,同时将所有产品的价格统计在一起,然后将总价格打印在底部。
如果我们没有数组,我们必须将每个产品存储在一个单独的变量中,然后调用打印的代码,并为每个产品单独添加。花费的时间要长得多,效率很低,而且也容易出错。如果我们有 10 个产品需要添加发票,那就只是有点麻烦而已,但是 100 个,或者 1000 个呢?我们稍后将在文章中使用这个例子。
像以前的文章一样,我们通过在 JavaScript 控制台中输入一些示例来了解数组的基础知识。我们在下面提供了一个(你也可以在单独的选项卡或窗口中打开此控制台,或者如果你愿意,请使用浏览器的开发者工具控制台)。
doctype html>
JavaScript console
* {
box-sizing: border-box;
}
html {
background-color: #0c323d;
color: #809089;
font-family: monospace;
}
body {
max-width: 700px;
}
p {
margin: 0;
width: 1%;
padding: 0 1%;
font-size: 16px;
line-height: 1.5;
float: left;
}
.input p {
margin-right: 1%;
}
.output p {
width: 100%;
}
.input input {
width: 96%;
float: left;
border: none;
font-size: 16px;
line-height: 1.5;
font-family: monospace;
padding: 0;
background: #0c323d;
color: #809089;
}
div {
clear: both;
}
var geval = eval;
function createInput() {
var inputDiv = document.createElement("div");
var inputPara = document.createElement("p");
var inputForm = document.createElement("input");
inputDiv.setAttribute("class", "input");
inputPara.textContent = ">";
inputDiv.appendChild(inputPara);
inputDiv.appendChild(inputForm);
document.body.appendChild(inputDiv);
if (document.querySelectorAll("div").length > 1) {
inputForm.focus();
}
inputForm.addEventListener("change", executeCode);
}
function executeCode(e) {
try {
var result = geval(e.target.value);
} catch (e) {
var result = "error — " + e.message;
}
var outputDiv = document.createElement("div");
var outputPara = document.createElement("p");
outputDiv.setAttribute("class", "output");
outputPara.textContent = "Result: " + result;
outputDiv.appendChild(outputPara);
document.body.appendChild(outputDiv);
e.target.disabled = true;
e.target.parentNode.style.opacity = "0.5";
createInput();
}
createInput();
|