gpt4 book ai didi

Javascript - 从字符串获取数组值

转载 作者:行者123 更新时间:2023-12-02 15:21:25 25 4
gpt4 key购买 nike

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

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

关于Javascript - 从字符串获取数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34018990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com