使用变量在某个索引处获取字符串

问题描述 投票:0回答:1

我是JavaScript的新手,我不确定为什么这不起作用。我正在尝试打印出字符串数组的特定索引内的内容。每次我得到一个undefined

我的JavaScript

const { log: $, warn: $w, error: $e } = console;
const btn = document.querySelector(".click");
const app = document.querySelector(".app2");
let pressed = 0;
let titleArray = [];

btn.addEventListener(`click`, () => {
  pressed++;
  titleArray.push(`Button pressed ${pressed}`);
  $(getArrayString(pressed));
  app.innerHTML += `
  <h1 class="title">Button pressed ${pressed}</h1>
`;
});

function getArrayString(pressed) {
  return titleArray[pressed];
}
<h1>Title</h1>
<div class="app">
  <h1 class="newtitle">Click this button</h1>
  <button class="click">Click me</button>
</div>

<div class="app2"></div>

为了确保我没有做任何非常错误的事情,我已经尝试过这样做,并且它们都能正常工作。

  const testNumb = 0;
  $(titleArray[0]);
  $(titleArray[0]);
  $(getArrayString());
//returns undefined until it the array gets big enough then it prints whatever is stored in index

function getArrayString() {
  return titleArray.toString();
}
javascript html dom
1个回答
0
投票

数组索引从0开始,但是在推入数组之前要递增pressed

因此,第一次单击时,将pressed设置为1,然后将Button pressed 1推入数组,但是它位于索引0处。当您使用getArrayString(pressed)时,它将尝试读取titleArray[1],但尚未填写,因此您会获得undefined

您应该等到调用getArrayString()之后再递增变量,或在调用时从变量中减去1。

© www.soinside.com 2019 - 2024. All rights reserved.