【发布时间】:2020-09-19 19:49:42
【问题描述】:
以下代码获取页面标题,将其与数组中的数据进行比较并输出最终值
var title = (document.title);
//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]
//function
function testfunction(array, variable){
var varindex = array.indexOf(variable)
return array[varindex+2]
}
//calling the function
testfunction(testarray, title)
var finalvalue = testfunction(testarray, title);
因此,如果我的页面标题是蓝色,它会给出我需要的值 110。 它工作正常,但这样我页面的唯一有效标题必须是 Blue,否则它将无法工作。
我希望能够拥有更长的页面标题,例如 Blue Shoes 。我尝试在开头添加以下变量以仅获取标题第一个单词
var fulltitle = (document.title);
var title = fulltitle.split(' ').slice(0,1);
但它不起作用。我的代码有什么问题? 谢谢
【问题讨论】:
-
试试 `title = fulltitle.trim().split(' ')[0]'
-
@Francesco 你可以检查我的答案,因为它通过了大部分测试用例。
标签: javascript arrays variables split title