繁体   English   中英

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];
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM