javascript - 如何使用 Javascript 将元素的内部 HTML 文本替换为数组的一部分

标签 javascript arrays for-loop if-statement innerhtml

我正在学习 JavaScript 类(class),为了进行练习,我们必须将一个数组与另一个数组进行比较,并仅使用两个数组中都存在的字符串值替换元素的内部 html 文本。这是 JavaScript:

// Here is an array of US State Capitals to use
var capitals = ["Montgomery", "Juneau", "Phoenix", "Little Rock", "Sacramento", "Denver", "Hartford", "Dover", "Tallahassee", "Atlanta", "Honolulu", "Boise", "Springfield", "Indianapolis", "Des Moines", "Topeka", "Frankfort", "Baton Rouge", "Augusta", "Annapolis", "Boston", "Lansing", "Saint Paul", "Jackson", "Jefferson City", "Helena", "Lincoln", "Carson City", "Concord", "Trenton", "Santa Fe", "Albany", "Raleigh", "Bismarck", "Columbus", "Oklahoma City", "Salem", "Harrisburg", "Providence", "Columbia", "Pierre", "Nashville", "Austin", "Salt Lake City", "Montpelier", "Richmond", "Olympia", "Charleston", "Madison", "Cheyenne"];



// Using JavaScript, get the contents of the "cities" div and convert it into an array of strings (each city will be an element in the array)
var citiesString = document.getElementById("cities").innerHTML;

var cities = citiesString.split(", ");


// Loop through the array of cities.  Compare each element to the array of capitals.  If a city is NOT a state capital, update the HTML output to leave out that city.  (Note: formatting, commas, etc. doesn't count -- just get the cities to display.)


for (i = 0; i < cities.length; i++) {
  if(capitals.indexOf(cities[i]) >=0) {
    document.getElementById("cities").innerHTML += cities[i] += ", ";
  } 
}

我让它只显示两个数组中存在的城市,但它仍然预先显示城市数组的整个列表。如何让它只显示“波士顿、印第安纳波利斯和亚特兰大”?

最佳答案

在for循环之前清除“城市”的内容。

document.getElementById("cities").innerHTML = "";

您将数组附加到元素中的现有文本中。

关于javascript - 如何使用 Javascript 将元素的内部 HTML 文本替换为数组的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48877699/

相关文章:

javascript - 在 mocha 中将变量从 before() 传递到 it()

javascript - 滚动时创建一个不断变化的 css 导航栏?

javascript - 如何对AJAX请求返回的JSON格式数据进行排序?

c - 二维零数组中的随机一

javascript - 如何用Js循环动态生成JSON?

javascript - 如何遍历对象数组以查找 ID 然后返回同级键

javascript - 当 Chromium 上的自动播放为 false 时,视频不会绘制在 Canvas 上

javascript - 将项目添加到状态内的数组时,渲染 React 应用程序不适用

javascript - 如何在 Javascript 中从多个数组中获取随机集?

c# - 计算字符串中的箭头