Javascript-从字符串中获取数组值

Javascript - Get array value from string

本文关键字:数组 获取 字符串 Javascript-      更新时间:2023-09-26

我想知道是否有任何方法可以基于字符串获取数组的值,并显示数组中的下一个值。

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