我正在使用JavaScript类,我需要将一个数组与另一个数组进行比较,并将元素的内部html文本替换为仅存在于BOTH数组中的字符串值。这是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] += ", ";
}
}
我只显示两个阵列中存在的城市,但它仍然显示城市阵列的整个列表。如何让它只显示“波士顿,印第安纳波利斯和亚特兰大”?
答案 0 :(得分:1)
在for循环之前清除'cities'的内容。
document.getElementById("cities").innerHTML = "";
您要将数组附加到元素中的现有文本。