Javascript-从字符串中获取数组值
Javascript - Get array value from string
我想知道是否有任何方法可以基于字符串获取数组的值,并显示数组中的下一个值。
<p id="current">page1</p>
<p id="next"></p>
<script>
var page = ["page1", "page2", "page3", "page4", "page5"];
if(document.getElementById("current") == page[0]){
document.getElementById("next").innerhtml = page[1]
};
</script>
这就是我的总体想法。然而,这会有很多if语句,看起来也不好看。所以我想知道是否有一种方法可以复制这种函数,而不需要包含太多if语句。
将代码与注释相结合是学习的好方法
// This is the list of pages you have.
var pages = ["page1", "page2", "page3", "page4", "page5"];
// We use the innerText attribute of the #current node to find out
// what the current page is as a string.
var current = document.getElementById("current").innerText;
// Use the indexOf method of pages to get the index of the current
// page in the list of pages.
var index = pages.indexOf(current);
// Now, check if there is a next page. We do so by checking if current
// is not the last page in the list, or rather, there is at least one
// more page in the list.
if (index < pages.length - 1) {
// If so, we set next to that page. Note that you can put an
// expression for the key when using bracket notation here!
var next = pages[index + 1];
} else {
// Otherwise, use other text.
var next = "No more pages :(";
}
// Now set the innerHTML of the #next node to the value of next.
document.getElementById("next").innerHTML = next;
您可以使用.indexOf
方法(更多信息)来查找您要查找的元素的数组索引。
小提琴:http://jsfiddle.net/0fu3dydy/
JavaScript
var page = ["page1", "page2", "page3", "page4", "page5"];
var currentPageIndex = page.indexOf(document.getElementById("current").innerHTML);
if (currentPageIndex < page.length - 1) {
document.getElementById("next").innerHTML = page[currentPageIndex + 1];
} else {
// Do something when the current element is also the last
}
只需包含一个for语句
<p id="current">page1</p>
<p id="next"></p>
<script>
var page = ["page1", "page2", "page3", "page4", "page5"];
for (i=0;i=page.length-1;i++) {
if(document.getElementById("current") == page[i]){
document.getElementById("next").innerhtml = page[i+1]
};
}
当数组中有多个值时,可以使用indexOf()
函数。
var currentIndex = page.indexOf(document.getElementById("current").textContent);
if(currentIndex > -1){
if((currentIndex + 1) == page.length){
// for last element
}else{
document.getElementById("next").innerhtml = page[currentIndex + 1];
}
}
相关文章:
- 从json子数组获取数据
- 从javascript数组获取php的日期时间
- 从表中的 JSON 数组获取数据
- 每个表的2D数组获取坐标JTSL,JAVASCRIPT
- javascript从元素到数组获取文本
- 如何从数组获取链接以在youtube Iframe API中播放
- JSON 编码多维数组获取值
- 如何从两个 JSON 数组获取增量
- 通过单击按钮数组获取隐藏 html 元素值的当前数组
- 在 JavaScript 中从内部数组获取数据
- 从数组获取非重复索引在 0 时失败
- JavaScript 从对象中的数组获取数组
- 如何通过 ajax 将 php 数组作为 javascript 数组获取
- 快速从 2D 数组获取索引,无需迭代 jquery
- 从 Nodejs socketio 数组获取所有套接字 id
- 无法动态从 json 数组获取数据
- 如何在javascript中使用数组获取和设置html标签的值
- jQuery对象数组获取一个项作为jQuery对象
- 如何在不向输出数组获取空值的情况下拆分字符串
- 从输入到数组获取数据