以下代码获取页面标题,将其与数组中的数据进行比较,并向我输出最终值
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);
但这不起作用。我的代码有什么问题?谢谢
这里的几个问题:
什么时候document.title
是Blue Shoes,然后您执行以下操作:
fulltitle.split(' ').slice(0,1)
它实际上返回一个类似的数组["Blue"]
。您需要先将其转换为文本,例如:
var title = fulltitle.split(' ').slice(0,1)[0];
另外,title
返回的值与testarray
数组变量("Blue" !== "blue"
)中的值不同,因此indexOf
不起作用。您需要将标题设置为小写,例如:
var varindex = array.indexOf(variable.toLowerCase())
工作演示:
var fulltitle = "Blue Shoes";
var arr = fulltitle.split(' ').slice(0, 1);
var title = arr && arr.length ? arr[0] : "";
//test variables
testarray = ["blue", "top", "110", "in stock", "red", "down", "111", "in stock"]
//function
function testfunction(array, variable) {
var varindex = array.indexOf(variable.toLowerCase())
return array[varindex + 2]
}
//calling the function
var finalvalue = testfunction(testarray, title);
console.log( finalvalue )
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句