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

时间:2015-12-01 11:13:23

标签: javascript arrays

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

<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语句。

4 个答案:

答案 0 :(得分:2)

将代码与注释相结合是一种很好的学习方式:

// 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;

答案 1 :(得分:0)

您可以使用.indexOf方法(more info)查找您要查找的元素的数组索引。

小提琴: 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
}

答案 2 :(得分:0)

只需添加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]
  };
}

答案 3 :(得分:0)

当您在数组中有多个值时,可以使用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];
   }
}