在js中如何获取一个hash对象的键值对,尤其

JavaScript015

在js中如何获取一个hash对象的键值对,尤其,第1张

var obj = { '1' : 'apple', '2' : 'orange', '3' : 'pear' }var arrMsg = ['apple', 'orange', 'pear']var array = [{'111': 'apple'}, {'222': 'orange'}]123456

for(var key in obj){

console.log(key) //输出为 1 2 3

console.log(obj[key])//输出为 apple orange pear}for(var (key,value) in obj){

console.log(key) //输出为 1 2 3

console.log(value)//输出为 apple orange pear}123456789

for(var val in arrMsg){

console.log(val) //输出为 apple orange pear}123

for(var i=0i<array.lengthi++){var item=array[i] var key=Object.keys(item)

console.log(item[key])//输出为 apple orange

示例:

*URL: https://www.baidu.com/?name=21002492_21_hao_pg

window.location和document.location互相等价的,可以交换使用

location的8个属性都是可读写的,但是只有href与hash的写才有意义。例如改变location.href会重新定位到一个URL,而修改location.hash会跳到当前页面中的anchor(<a id="name">或者<div id="id">等)名字的标记(如果有),而且页面不会被重新加载

注意

URL: https://www.baidu.com/?name=21002492_21_hao_pg#test?test1=1

search:"?name=21002492_21_hao_pg" 第一个"?"之后

hash:"#test?test1=1"第一个"#"之后的内容

注意上面的search和hash的区别,如果URL中“?”之前有一个“#”比如:“ https://www.baidu.com/#/test?name=21002492_21_hao_pg ”那么使用window.location.search得到的就是空(“”)。因为“?name=21002492_21_hao_pg”串字符是属于“#/test?name=21002492_21_hao_pg”这个串字符的,也就是说查询字符串search只能在取到“?”后面和“#”之前的内容,如果“#”之前没有“?”search取值为空。

现在前端会使用大量的框架来搭建前端页面应用,比如vue,当开启hash模式的时候,在实例外部方法无法使用this.$route时,老方法window.location.search也获取不到,这时需要使用window.location.hash来获取参数

兼容hash模式与非hash模式的方法:

第一步生成md5 hash串:

var reader = new FileReader()

reader.onload = function(callback) {

var md5 = rstr2hex(binl2rstr(binl_md5(reader.result, reader.result.length)))

}

document.getElementById("xxx").value=md5

第二步:获取生成的md5值

var md5value = document.getElementById('xxx').value